Can I use one SimpleDateFormat template for dates with suffixes "Z" and "+1: 00"?

I am calling a service that returns GMT dates. It has been working fine since November, but now with active daylight saving time, it fails. Here's an example of a date from daylight saving time:



And one of today's (in summer):



I used to use 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 ParseExcepton ("Unparsable date ..."). So, is it possible to use the same pattern for both, and if so, what is it? If I cannot use one pattern for both, what is the correct pattern for the second date above?

It shouldn't make any difference, but if used on Android platform.


source to share

3 answers

It definitely matters that you are using Android, as it might matter in this case if you were using Java 5/6 or 7.

The pattern you are using specifies the literal 'Z' (also 'T') to parse. It doesn't parse the timezone. You need to strip the single quotes around the "Z" to start parsing the actual time zone.

According to Android JavaDoc , it is not clear if capital Z would work in this case even as an hour / minute format rather specific. I don't know enough about the Android SDK to confirm, but the colon definitely changes the standard Java.



The new ISO8601 timezone pattern is covered by the pattern specifier X

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 might make a difference. You need to either disassemble it (partially) yourself, or grab Joda Time .



If you are using java6 you will have to identify templates and then apply formater

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    String date2Str="2011-12-07T15:50:01Z";
    Date date2 = df.parse(date2Str);

    SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
    String date1Str="2012-03-26T11:05:01GMT+01:00";
    Date date1 = df2.parse(date1Str);





All Articles