Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use one SimpleDateFormat pattern for dates with both 'Z' and '+1:00' suffixes?

I call a service which returns GMT dates. Its been working fine since November, but now with daylight savings time active, its failing. Here's a sample date from non-daylight savings time:

2011-12-07T15:50:01Z

And one from today (in daylight savings time):

2012-03-26T11:05:01+01:00

Previously I've been using this pattern:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.UK);

But its failing on the second date above with a ParseExcepton ("Unparsable date..."). So, can one pattern be used for both, and if so what is it? If I can't use one pattern for both, what is the correct pattern for the second date above?

It shouldn't make a difference, but if it does this is in use on the Android platform.

like image 677
Chris Knight Avatar asked Dec 30 '25 22:12

Chris Knight


2 Answers

It definitely makes a difference that you're using Android, as it would make a difference in this case if you were using Java 5/6 or 7.

The pattern you're using specifies a literal 'Z' (also 'T') to be parsed. It is not parsing a timezone. You need to drop the single-quotes from around the 'Z' to start parsing an actual time-zone.

According to the Android JavaDoc, it is unclear whether a capital Z will even work in this case, as the format of the hours/minutes is pretty specific. I don't know enough about the Android SDK to confirm, but the colon definitly makes a difference in standard Java.

like image 93
Spencer Kormos Avatar answered Jan 02 '26 10:01

Spencer Kormos


The new ISO8601 time zone pattern is covered by the X pattern specifier which is introduced in Java 7.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.UK);

If you're still on Java 6 or older, then yes it may make difference. You'll need either to parse it (partially) yourself or to grab Joda Time.

like image 29
BalusC Avatar answered Jan 02 '26 10:01

BalusC