Java – Can I use a SimpleDateFormat pattern for dates with the ‘Z’ and ‘+1:00’ suffixes?

Can I use a SimpleDateFormat pattern for dates with the ‘Z’ and ‘+1:00’ suffixes?… here is a solution to the problem.

Can I use a SimpleDateFormat pattern for dates with the ‘Z’ and ‘+1:00’ suffixes?

I called a service that returns the GMT date. It has been working well since November, but now that daylight saving time is in effect, it has failed. The following are example dates for non-daylight saving time:

2011-12-07T15:50:01Z

There is also one more from today (daylight saving time):

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

I’ve been using this pattern before:

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

But it fails on the second date above with ParseExcepton (“Unresolved date…”). So, is it possible to use one pattern 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 be any different, but if anything, this is what is used on the Android platform.

Solution

It will certainly be different if you are using

Android, since in this case it will be different if you are using Java 5/6 or 7.

The pattern you are using specifies the literal “Z” (also known as “T”) to parse. It does not resolve time zones. You need to remove the single quotes around the “Z” to start parsing the actual time zone.

According to Android JavaDoc It’s not clear if an uppercase Z works in this case, as the hour/minute format is pretty specific. I don’t know enough about the Android SDK to confirm, but colons do differ in standard Java.

Related Problems and Solutions