Search code examples
javadatedatetimejodatimedatetime-format

DateFormatter is not printing value in the given format


My date-time format string is : yyyy-MM-dd'T'HH:mm:ss.SSSZ
I am using DateTimeFormatter from Joda Time to print my date in the above mentioned format.

Now, consider the date as

2016/04/01 23:00:00

then it should have printed

2016-04-01T23:00:00.000Z

But, it prints

2016-04-01T23:00:00.000+0200

Please help me in getting the date printed in the same format as specified in the string format.


Solution

  • According https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html Z has special meaning:

    Z       zone-offset
    

    If you want to escape Z quote Z with ':

    yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
    

    For example:

    java.time.LocalDateTime date = java.time.LocalDateTime.now();
    java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
                    .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    java.lang.String text = date.format(formatter);
    System.out.println(text);
    

    prints

    2016-06-11T18:39:41.962Z