Search code examples
javadatetimelocaldate

Java Date Time as ISO_DATE_TIME


I want to add a Z at the end of DateTimeFormatter ISO_DATE_TIME in Java not hard coded

String sample = "2018-05-11T13:35:11Z";

DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[.SSS][XXX][X]");

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

LocalDateTime newLocalDateTime = LocalDateTime.parse(sample, df1);

System.out.println(newLocalDateTime.toString());

Output is:

2018-05-11T13:35:11

I want the output to be 2018-05-11T13:35:11Z


Solution

  • You are calling toString() of your LocalDateTime, you should be calling format. Change

    System.out.println(newLocalDateTime.toString());
    

    to

    System.out.println(newLocalDateTime.format(df1));
    

    Outputs

    2018-05-11T13:35:11Z