0

I don't really get how to make my date format into this: 2013-09-03T06:19:57.802Z I'm accessing an API that needs my date to be in this format. So when the format is wrong, I'm recieving an internal server error. I've done the following so far.

SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US);
Date date = new Date();
String dateToday = ISO8601DATEFORMAT.format(date);

I'm getting this one. 2013-09-03T14:28:11+0800

Any ideas? Thanks!

Luke Villanueva
  • 2,030
  • 8
  • 44
  • 94

2 Answers2

2

It's using in the format string Z as a time zone specifier, rather than as a literal Z character. One simple approach is to:

  • Set the time zone in the format to UTC
  • Escape the Z

So it would look like this:

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",
                                                  Locale.US);
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date();
String dateToday = isoFormat.format(date);

In fact you don't need to escape the Z, as if the offset is 0 then a Z will be used anyway instead of +00. The important part is to set the time zone in the formatter. Whether you want to escape the Z or not depends on which approach you find most readable.

Another alternative would be to use Joda Time which is a much cleaner date/time API in general, and has ISO formatting built in :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

I think you need a format like this

SimpleDateFormat ISO8601DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
AnujMathur_07
  • 2,586
  • 2
  • 18
  • 25