在Java 8中仅将日期解析为LocalDateTime [英] Parse date-only as LocalDateTime in Java 8

查看:673
本文介绍了在Java 8中仅将日期解析为LocalDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析一个有时作为日期而有时作为日期/时间的字段。是否可以使用Java 8时间API为此使用单一数据类型?
目前,我尝试使用LocalDateTime,但用于跟随调用 LocalDateTime.parse(1986-04-08,DateTimeFormatter.ofPattern(yyyy-MM-dd))
我得到了

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.

推荐答案

只需使用构建器 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();

此格式化程序使用 [] 括号允许格式中的可选部分,并添加小时 HOUR_OF_DAY ,分钟 MINUTE_OF_HOUR 和第二<$ c $>的默认值c> SECOND_OF_MINUTE 。

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.

并像往常一样使用它。

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

这会输出正确的日期时间,默认小时数为0(从当天开始)。

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

这篇关于在Java 8中仅将日期解析为LocalDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆