Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat ignores "XXX" if timezone is set to "UTC"

I am trying to output the current datetime as UTC in the following format: 2016-01-11T14:08:42+00:00

final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));

final String dateString = formatter.format(new Date());

"dateString" should now contain "2016-01-11T14:08:42+00:00" but it contains "2016-01-11T14:08:42Z".

Without the "UTC" timezone setting I get the right format but - of course - in my specific timezone...

Any ideas?

like image 615
eventhorizon Avatar asked Jan 11 '16 14:01

eventhorizon


People also ask

What is T & Z in UTC time format?

The T separates the date portion from the time-of-day portion. The Z on the end means UTC (that is, an offset-from-UTC of zero hours-minutes-seconds). The Z is pronounced “Zulu”.

What is the difference between DateFormat and SimpleDateFormat?

The java SimpleDateFormat allows construction of arbitrary non-localized formats. The java DateFormat allows construction of three localized formats each for dates and times, via its factory methods.

What is UTC date format in Java?

Parse String to ZonedDateTime in UTC Date time with full zone information can be represented in the following formats. dd/MM/uuuu'T'HH:mm:ss:SSSXXXXX pattern. e.g. "03/08/2019T16:20:17:717+05:30" . MM/dd/yyyy'T'HH:mm:ss:SSS z pattern.


1 Answers

See the documentation for SimpleDateFormat:

For formatting [using an ISO 8601 Time zone], if the offset value from GMT is 0, "Z" is produced.

So, this behaviour is expected.

You can either:

  • Use the RFC 822 timezone formatter ZZZ; however, this produces "+0000"
  • Manipulate the string to replace the final Z: str.replaceAll("Z$", "+00:00")
like image 138
Andy Turner Avatar answered Sep 24 '22 12:09

Andy Turner