Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

2022-01-14T00:00:00

Any suggestion?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading