Parse date-only as LocalDateTime in Java 8

前端 未结 3 1651
我在风中等你
我在风中等你 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:49

    I know its late for the answer, but it can help others...

    Since the LocalDateTime you need to set a time, otherwise you can use just the LocalDate, I searched for LocalDateTime built-in solution to handle this. I didn't found, however I used this following approach:

    // For specific date (the same as the question)
    LocalDateTime specificDate LocalDateTime.of(LocalDate.of(1986, 4, 8), LocalTime.MIN);
    

    Other examples:

    // For the start of day
    LocalDateTime startToday = LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
    
    // For the end of day
    LocalDateTime endOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
    

    This way you don't need to use a formatter. :)

提交回复
热议问题