java 限制日期格式,使用新的Java 8 DateTimeFormatter进行严格的日期解析

I have a simple problem : I want to parse Java strings in format "yyyyMMdd" strictly, so that "19800229" is a valid date, but "19820229" is not. Assume these are AD dates from the normal Gregorian calendar.

I am trying to use the new java.time package from JDK 8 to solve this problem, but it is proving more complicated than hoped. My current code is:

private static final DateTimeFormatter FORMAT = DateTimeFormatter

.ofPattern("yyyyMMdd").withChronology(IsoChronology.INSTANCE)

.withResolverStyle(STRICT);

public static LocalDate parse(String yyyyMMdd) {

return LocalDate.parse(yyyyMMdd, FORMAT);

}

However, parsing a valid date such as "19800228" produces what to me is an incomprehensible error:

java.time.format.DateTimeParseException: Text '19820228' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=2, DayOfMonth=28, YearOfEra=1982},ISO of type java.time.format.Parsed

How do I use java.time.format.DateTimeFormatter to solve my simple use case?

解决方案

I'm editing to limit what kind of string will be considered valid by using a custom formatter created with a DateTimeFormatterBuilder.

public class DateFormmaterTest {

static DateTimeFormatter CUSTOM_BASIC_ISO_DATE = new DateTimeFormatterBuilder()

.parseCaseInsensitive().appendValue(YEAR, 4)

.appendValue(MONTH_OF_YEAR, 2).appendValue(DAY_OF_MONTH, 2)

.optionalStart().toFormatter()

.withResolverStyle(ResolverStyle.STRICT)

.withChronology(IsoChronology.INSTANCE);

public static void main(String[] args) {

LocalDate date1 = LocalDate.parse("19800228-5000",

CUSTOM_BASIC_ISO_DATE);

System.out.println(date1);

}

}

2/29/1982 is invalid and would throw the following:

Caused by: java.time.DateTimeException: Invalid date 'February 29' as '1982' is not a leap year

at java.time.LocalDate.create(LocalDate.java:429)

A date of 19800228-5000 would work with BASIC_ISO_DATE because it allows the optional offset which you don't want allowed. My CUSTOM_BASIC_ISO_DATE formatter will not allow that and throw the following:

Exception in thread "main" java.time.format.DateTimeParseException: Text '19800228-5000' could not be parsed, unparsed text found at index 8.

Note, if you are sure of the string length, yyyyMMdd then you could always work with the substring of first 8 chars to negate the need for the resolver. However that is two different things. The resolver will flag invalid date formats on input and the substring would of course just strip the extra chars out.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值