tags:

views:

101

answers:

1

If I execute:

System.out.println("Formatter: " + String.format("%1$tH:%1$tM:%1$tS %1$tz %1$tZ", now));
System.out.println("SimpleDF : " + new SimpleDateFormat("HH:mm:ss Z z").format(now));

I expect the result to be the same. If I check the automatically adjust for daylight savings time the values start to vary:

without dst (as expected, gmt=9:48):
Formatter: 10:48:16 +0100 GMT+01:00
SimpleDF : 10:48:16 +0100 GMT+01:00
with dst (gmt varies between formatter and sdf ???):
Formatter: 11:47:54 +0100 CEST
SimpleDF : 11:47:54 +0200 CEST

Running on win xp, with same results on java 1.6-10/13 and 1.5.0-14, locale en_US. What do you think, a bug?

Perhaps related: http://bugs.sun.com/view_bug.do?bug_id=6286592.

+1  A: 

The correct way is to use the SimpleDateFormat (or rather a DateFormat) object. String.format is to format strings returned as a result of invocation of the toString() method over the object passed. The first line of code can be broken down to something like,

String temp = now.toString(); System.out.println("Formatter: " + String.format("%1$tH:%1$tM:%1$tS %1$tz %1$tZ", temp));

The temporary string object is formatted using the default locale and settings, and hence, may not guarantee a perfect result (per my experience).

SimpleDateFormat() works over the Date object and accesses attributes and makes sure of all DST patches.

Sandy