convert String “yyyy-MM-dd” to LocalDateTime

[亡魂溺海] 提交于 2019-12-03 10:41:42
Jens

Use LocalDate to create a localDate and then you can add the timepart if you need it:

    DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDate ld = LocalDate.parse("2017-03-13", DATEFORMATTER);
    LocalDateTime ldt = LocalDateTime.of(ld, LocalDateTime.now().toLocalTime());
    System.out.println(ldt);

or LocalDateTime

ldt = LocalDateTime.of(ld, LocalDateTime.MIN.toLocalTime());

if you just need an empty timepart

EDIT:

Look at this solution with this you can build your dynamic parser:

    DateTimeFormatter DATEFORMATTER1 = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    DateTimeFormatter DATEFORMATTER = new DateTimeFormatterBuilder().append(DATEFORMATTER1)
    .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
    .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
    .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
    .toFormatter();

    //DateTimeFormatter DATEFORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDateTime ldt = LocalDateTime.parse("2017-03-13", DATEFORMATTER);

You can not convert "2017-03-13" to a LocalDateTime since there is no time information in the string, only date. You can convert it to a LocalDate

DateTimeFormatter dateformatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate ld = LocalDate.parse("2017-03-13", dateformatter);

after this we can covert it to LocalDateTime

LocalDateTime ldt = ld.atStartOfDay();
Vinayak Shenoy

For start of the day you can use:

LocalDate.parse("2017-10-18", DateTimeFormatter.ofPattern("yyyy-MM-dd"))
.atStartOfDay().atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_DATE_TIME)

For end of the day you can use:

LocalDate.parse("2017-10-18", DateTimeFormatter.ofPattern("yyyy-MM-dd"))                        
.atStartOfDay().plusHours(23).plusMinutes(59).plusSeconds(59).atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ISO_DATE_TIME)

For localDateTime you can use:

LocalDate.parse("2017-10-18", DateTimeFormatter.ofPattern("yyyy-MM-dd")).atTime(LocalTime.now())
.atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"))

Result:

2017-10-18T00:00:00Z
2017-10-18T23:59:59Z
2017-10-18T14:45:35Z

How about a one liner?

LocalDateTime.parse("2017-03-13" + " 00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm"));

Use Joda-Time-XX.jar it has DateTimeFormatter to convert date to date time format. Either you can provide date time in (yyyy-MM-dd HH:mm:ss format) or date alone. In both the cases you will get date and time.

DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime dateTime =  dateTimeFormatter.parseDateTime(date);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!