views:

404

answers:

3

I am trying to parse a date that looks like this:

2010-04-05T17:16:00Z

This is a valid date per http://www.ietf.org/rfc/rfc3339.txt. The 'Z' literal "imply that UTC is the preferred reference point for the specified time."

If I try to parse it using SimpleDateFormat and this pattern:

yyyy-MM-dd'T'HH:mm:ss

It will be parsed as a Mon Apr 05 17:16:00 EDT 2010

SimpleDateFormat is unable to parse the string with these patterns:

yyyy-MM-dd'T'HH:mm:ssz
yyyy-MM-dd'T'HH:mm:ssZ

I can explicitly set the TimeZone to use on the SimpleDateFormat to get the expected output, but I don't think that should be necessary. Is there something I am missing? Is there an alternative date parser?

A: 

The time zone should be something like "GMT+00:00" or 0000 in order to be properly parsed by the SimpleDateFormat - you can replace Z with this construction.

Cornel Creanga
+5  A: 

In the pattern, the inclusion of a 'z' date-time component indicates that timezone format needs to conform to the General time zone "standard", examples of which are Pacific Standard Time; PST; GMT-08:00.

A 'Z' indicates that the timezone conforms to the RFC 822 time zone standard, e.g. -0800.

I think you need a DatatypeConverter ...

@Test
public void testTimezoneIsGreenwichMeanTime() throws ParseException {
    final Calendar calendar = javax.xml.bind.DatatypeConverter.parseDateTime("2010-04-05T17:16:00Z");
    TestCase.assertEquals("gotten timezone", "GMT+00:00", calendar.getTimeZone().getID());
}
Paul McKenzie
yes, I understand that. The z/Z permutations were just me seeing if anything would stick. It still remains that my date is valid and there should be a valid pattern to parse it.
DanInDC
I was struggling to remember the class `DatatypeConverter` which a colleague showed me only recently.
Paul McKenzie
Also see previous http://stackoverflow.com/questions/2201925/converting-iso8601-compliant-string-to-java-util-date answer
Paul McKenzie
Thanks, I haven't seen this class before. It also seems there is finally a BASE64 en/decoder in the standard jdk classes :)
Jörn Horstmann
+2  A: 

The restlet project includes an InternetDateFormat class that can parse RFC 3339 dates.

Restlet InternetDateFormat

Though, you might just want to replace the trailing 'Z' with "UTC" before you parse it.

Marcus Adams
Restlet InternetDateFormat worked well for me
Mike