Java SimpleDateFormat Timezone offset with minute separated by colon

You can get the timezone offset formatted like +01:00 with the SimpleDateFormat in Java 7 (yyyy-MM-dd'T'HH:mm:ss.SSSXXX), or with the Joda's DateTimeFormat (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).


Here’s the 2017 answer. If there is any way you can (which there is), throw the outdated classes like SimpleDateFormat overboard and use the modern and more convenient classes in java.time. In particular, the desired format, 2012-11-25T23:50:56.193+01:00 complies with ISO-8601 and therefore comes out of the box with the newer classes, just use OffsetDateTime.toString():

    OffsetDateTime time = OffsetDateTime.now();
    System.out.println(time.toString());

This prints something like

2017-05-10T16:14:20.407+02:00

One thing you may or may not want to be aware of, though, it prints as many groups of 3 decimals on the seconds as it takes to print the precision in the OffsetDateTime object. Apparently on my computer “now” comes with a precision of milliseconds (seconds with three decimals).

If you have an oldfashioned Date object, for example, you got it from a call to some legacy method, I recommend the first thing you do is convert it to Instant, which is one of the modern classes. From there you can easily other conversions depending on your requirements:

    Date now = new Date();
    OffsetDateTime time = now.toInstant().atZone(ZoneId.systemDefault()).toOffsetDateTime();
    System.out.println(time.toString());

I am really doing more conversions than necessary. atZone(ZoneId.systemDefault()) produced a ZonedDateTime, and its toString() will not always give you the format you said you wanted; but it can easily be formatted into it:

    ZonedDateTime time = now.toInstant().atZone(ZoneId.systemDefault());
    System.out.println(time.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));