leozilla
leozilla

Reputation: 1346

Formating java Date with java.time.DateTimeFormatter including time offset

I am currently struggling to refactor this piece of old code to use the new java.time.format.DateTimeFormatter because it is used in our main logging component where this creates unnecessary garbage.

private String getFormattedDate(final Date date) {
    // a new instance is created foreach log message 
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
    return dateFormat.format(date);
}

I already tried the new ISO_INSTANT formater like:

DateTimeFormatter.ISO_INSTANT.format(date.toInstant());

but this gives (slightly) different output as before.

My test shows:

Expected: is "2013-10-22T05:23:48.397+0200"
 but: was "2013-10-22T03:23:48.397Z"

So I need the time zone offset to be included in the format string as shown in Expected.

I know about the DateTimeFormatterBuilder but I didnt manage to build it in a way to get my desired format output.

How would I need to do this? I know I can always fall back to using a single thread local SimpleDateFormat instance but I would like to use the new java.time stuff :-)

Upvotes: 1

Views: 349

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

Date date = new Date();

System.out.println(DateTimeFormatter.ISO_INSTANT.format(date.toInstant()));
// output: 2015-11-22T14:46:08.776Z

System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(
       date.toInstant().atZone(ZoneId.systemDefault())));
// output: 2015-11-22T15:46:08.776+01:00

System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME
                                    .withZone(ZoneId.systemDefault())
                                    .format(date.toInstant()));
// output: 2015-11-22T15:46:08.776+01:00

Upvotes: 2

Related Questions