There’s a problem with SimpleDateFormat (and presumably DateFormat) in Android. Based off this closed ticket, TimeZones applied to a SimpleDateFormat object will correctly modify the date itself, but won’t change the TimeZone being output under format Z.

	String date = "2010-06-12 08:00:00+800";
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
    	Date d = null;

    	try
    	{
    		d = sdf.parse(date);
    	}
    	catch(Exception e) {e.printStackTrace();}
    	
    	// note: my locale is Australia/Perth (GMT+8)
    	Log.e("DateTest Original", sdf.format(d));
    	
    	sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    	Log.e("DateTest Modified", sdf.format(d));

And our output?


DateTest Original 2010-06-12 08:00:00+0800
DateTest Modified 2010-06-12 00:00:00+0800

As you can see, while the time shift was applied correctly (-8 hours), the zone prints badly. Very irritating! On the bright side, it’s pretty easy to fix.

private static String fixUTC(String date)
{
	return date.replaceAll("(\\d+-\\d+-\\d+T\\d+:\\d+:\\d+)([-+]\\d+)", "$1+0000");
}

(As an aside, escaping regex in Java is a pain)

Advertisements