-2

I have a problem formatting a date. I want the following output:

yyyy-MM-ddTHH:mm:ss+02:00

Where +02:00 depends on the timezone where you are, in my case Europe/Amsterdam

I have this function:

public String marshal(Date d) throws Exception
{
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    String s = formatter.format(d);

    return s;
}

But it gives me:

2017-05-10T14:56:46+0200

How can I have the timezone hour/minute with an extra colon in between?

baliman
  • 588
  • 2
  • 8
  • 27
  • 1
    Try "yyyy-MM-dd'T'HH:mm:ssXXX". See http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html – bradimus May 10 '17 at 13:08
  • 1
    This format is defined by the ISO 8601 standard. Search Stack Overflow for "ISO 8601" to see many existing posts. And you should always search thoroughly before posting. Another thing, avoid the old legacy date-time classes you are using; now supplanted by the java.time classes. – Basil Bourque May 10 '17 at 15:51
  • This appears to have been asked and answered already: [http://stackoverflow.com/a/16289344/7750124](http://stackoverflow.com/a/16289344/7750124) However I would read into the documentation as @f1sh explained as it would help you understand your problem better. The solution in the link above appears to point to the same answer. – Koshux May 10 '17 at 13:21
  • I could not have said that better than @BasilBourque. baliman and anyone else with the same question, you may start with [my answer to the linked question](http://stackoverflow.com/a/43895243/5772882). – Ole V.V. May 10 '17 at 18:09

1 Answers1

3

It's right there in the documentation:

The number of pattern letters designates the format for both formatting and parsing as follows [...]

And from the examples:

"yyyy-MM-dd'T'HH:mm:ss.SSSXXX" 2001-07-04T12:08:56.235-07:00

Meaning that the colon-separated version of the timezone can be expressed using "XXX" in the pattern.

TL;DR: use

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
f1sh
  • 11,489
  • 3
  • 25
  • 51