java localdatetime解析,Java8 LocalDateTime解析错误

I am trying to parse the following timestamp string 03-feb-2014 13:16:31 using java.time but it is throwing an error. Here is my code.

String timestamp = "03-feb-2014 13:16:31";

DateTimeFormatter format;

DateTimeFormatterBuilder formatBuilder = new DateTimeFormatterBuilder();

formatBuilder.parseCaseInsensitive();

formatBuilder.append(DateTimeFormatter.ofPattern("dd-MMM-YYYY HH:mm:ss"));

format = formatBuilder.toFormatter();

LocalDateTime localdatetime = LocalDateTime.parse(timestamp, format);

But I am getting the following error.

Exception in thread "main" java.time.format.DateTimeParseException: Text '03-feb-2014 13:16:31' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfMonth=3, MonthOfYear=2, WeekBasedYear[WeekFields[SUNDAY,1]]=2014},ISO resolved to 13:16:31 of type java.time.format.Parsed

at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)

at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)

at java.time.LocalDateTime.parse(LocalDateTime.java:492)

at com.target.util.CntrlmProcessor.main(CntrlmProcessor.java:24)

Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {DayOfMonth=3, MonthOfYear=2, WeekBasedYear[WeekFields[SUNDAY,1]]=2014},ISO resolved to 13:16:31 of type java.time.format.Parsed

at java.time.LocalDateTime.from(LocalDateTime.java:461)

at java.time.format.Parsed.query(Parsed.java:226)

at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)

From the error it looks like the library has been able to parse the string as it separated out all the fields from the timestamp, but there seems to be something that I am missing.

I tried to parse just the time part of the timestamp alone and that is working just fine.

解决方案

If you use yyyy instead of YYYY in your pattern, the code you've given works. YYYY is "week-based year" which would normally only be used if you're also specifying week number and day-of-week (e.g. a pattern of YYYY-ww-EEE). This is pretty rare.

Note that even just "year" has yyyy and uuuu - yyyy is "year of era" (which is always non-negative - and always positive in the Gregorian calendar) whereas uuuu is a sort of "eraless year" - for example, 5BCE is -4 as an eraless year. If you don't need to deal with dates before the common era (or dates in other calendar systems) you probably don't need to worry about this.

I would also suggest rewriting your code as:

DateTimeFormatter format = new DateTimeFormatterBuilder()

.parseCaseInsensitive()

.appendPattern("dd-MMM-yyyy HH:mm:ss")

.toFormatter();

... just for simplicity.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值