Convert specific format from string to LocalDateTime

I have this method:

   private static LocalDateTime setActivationDate(final String date) {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyy");
        LocalDate ld = LocalDate.parse(date, dateFormatter);
        return LocalDateTime.of(ld, LocalDateTime.MIN.toLocalTime());
    }

When i pass value dd.MM.yyyy for example: 14.01.2022 i get this:

2022-01-14T00:00

But I want to return and seconds also..so that format looks like this:

2022-01-14T00:00:00

Any suggestion?


Solution 1:

LocalDateTime omits the seconds when they are 00. If you want to get them use the ISO_LOCAL_DATE_TIME formatter:

String date = "14.01.2022";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyy");
LocalDate ld = LocalDate.parse(date, dateFormatter);

LocalDateTime ldt = LocalDateTime.of(ld, LocalTime.MIDNIGHT);

System.out.println(ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

Prints

2022-01-14T00:00:00

If you take a look at the docs, toString explains the behaviour:

Outputs this date-time as a String, such as 2007-12-03T10:15:30. The output will be one of the following ISO-8601 formats:

uuuu-MM-dd'T'HH:mm

uuuu-MM-dd'T'HH:mm:ss

uuuu-MM-dd'T'HH:mm:ss.SSS

uuuu-MM-dd'T'HH:mm:ss.SSSSSS

uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS

The format used will be the shortest that outputs the full value of the time where the omitted parts are implied to be zero.