Parse date-only as LocalDateTime in Java 8

前端 未结 3 1658
我在风中等你
我在风中等你 2020-12-20 19:09

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 a

3条回答
  •  我在风中等你
    2020-12-20 19:28

    Jose's answer using parseDefaulting is nice. There's also another alternative, if you don't want to use a DateTimeFormatterBuilder.

    First you create your formatter with an optional section - in this case, the time-of-day part, delimited by []:

    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd[ HH:mm:ss]");
    

    Then you call parseBest, providing the String to be parsed and a list of method references:

    TemporalAccessor parsed = fmt.parseBest("1986-04-08", LocalDateTime::from, LocalDate::from);
    

    In this case, it'll first try to create a LocalDateTime, and if it's not possible, it'll try to create a LocalDate (if none is possible, it'll throw an exception).

    Then, you can check which type is returned, and act accordingly:

    LocalDateTime dt;
    if (parsed instanceof LocalDateTime) {
        // it's a LocalDateTime, just assign it
        dt = (LocalDateTime) parsed;
    } else if (parsed instanceof LocalDate) {
        // it's a LocalDate, set the time to whatever you want
        dt = ((LocalDate) parsed).atTime(LocalTime.MIDNIGHT);
    }
    

    If the result is a LocalDate, you can choose to call atStartOfDay(), as suggested by others, or change to a specific time-of-day, such as atTime(LocalTime.of(10, 30)) for 10:30 AM, for example.

提交回复
热议问题