Search code examples
javajava-timedatetimeformatter

Parsing LocalDate to ZonedDateTime in correct format


Given:

public static void main(String[] args) {

   String dateString = "2018-07-30T13:36:17.820";

    DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
            .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");

    LocalDate date = LocalDate.parse(dateString, DATE_TIME_FORMATTER);

    ZonedDateTime zonedDateTime = date.atStartOfDay((ZoneOffset.UTC));

    System.out.println(zonedDateTime);
}

And output:

2018-07-30T00:00Z

...what is the pattern to print seconds? Stupid question no doubt but driving me a little nuts

I need:

2018-07-30T00:00:00Z

Solution

  • I changed java.time.LocalDate to java.time.LocalDateTime, you need it if you want to show also the seconds.

    package com.test;
    
    import java.time.LocalDateTime;
    import java.time.ZoneOffset;
    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    
    public class DateFormatter {
    
        public static void main(String[] args) {
    
            String dateString = "2018-07-30T13:36:17.820";
    
            DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
                    .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    
            LocalDateTime date = LocalDateTime.parse(dateString, DATE_TIME_FORMATTER);
    
            ZonedDateTime zonedDateTime = date.atZone(ZoneOffset.UTC);
    
    
            System.out.println(zonedDateTime);
        }
    }
    

    Output is:

    2018-07-30T13:36:17.820Z