localdatetime 默认时间_在Java 8中仅将日期解析为LocalDateTime

I need to parse a field which is sometimes given as a date and sometimes as a date/time. Is it possible to use single datatype for this using Java 8 time API?

Currently, I attempted to use a LocalDateTime for it, but for following invocation LocalDateTime.parse("1986-04-08", DateTimeFormatter.ofPattern("yyyy-MM-dd"))

I get a

java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 1986-04-08 of type java.time.format.Parsed

This is part of some generic parser accepting a date/datetime parse pattern as configuration option. So e.g. following solution with hardcoded parsing pattern

if ("yyyy-MM-dd".equals(pattern)) {

LocalDate.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd"))).atStartOfDay()

}

is not an option for me.

Any other suggestions how to code it in a clean way are welcome.

解决方案

Just create custom formatter with the builder DateTimeFormatterBuilder

DateTimeFormatter formatter = new DateTimeFormatterBuilder()

.appendPattern("yyyy-MM-dd[ HH:mm:ss]")

.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)

.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)

.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)

.toFormatter();

This formatter uses the [] brackets to allow optional parts in the format, and adds the default values for hour HOUR_OF_DAY, minute MINUTE_OF_HOUR and second SECOND_OF_MINUTE.

note: you can ommit, minutes and seconds, just providing the hour is enough.

And use it as usual.

LocalDateTime localDateTime1 = LocalDateTime.parse("1994-05-13", formatter);

LocalDateTime localDateTime2 = LocalDateTime.parse("1994-05-13 23:00:00", formatter);

This outputs the correct date time with default hours of 0 (starting of the day).

System.out.println(localDateTime1); // 1994-05-13T00:00

System.out.println(localDateTime2); // 1994-05-13T23:00

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值