Question

Can anyone please explain to me how is it possible for the following code to output 01:00:00

System.out.println(new SimpleDateFormat("HH:mm:ss").format(0));

And if I change the amount of milliseconds from 0 to anything higher, it will consistently output 1 hour more than it should.

Edit: This doesn't make any sense at all, but it works! Even the "official" GMT website, http://wwp.greenwichmeantime.co.uk/ confirms that the timezone that I see and use on my local machine is GMT+0, yet in order to obtain the desired result, I first had to set the SimpleDateFormat's Timezone to GMT+0.

Edit 2: OK, so from a logical point of view, the SimpleDateFormat defaults to a time in history when Britain was GMT+1. This is very unexpected and confusing for anyone trying to simply parse a relatively low amount of time using SimpleDateFormat.

Was it helpful?

Solution

Look at Wikipedia about British Summer Time experiment. Citing:

"A further inquiry during 1966–67 led the government of Harold Wilson to introduce the British Standard Time experiment, with Britain remaining on GMT+1 throughout the year. This took place between 27 October 1968 and 31 October 1971, when there was a reversion to the previous arrangement."

Remember that the strange expression format(0) effectively relates to date 1970-01-01.

Update: Remark about OPs edits and (deleted) comments: It is a big difference if the time zone parameter implicitly given to SimpleDateFormat (implicitly because of default system configuration) is specified as "Europe/London" (then GMT+1 in year 1970 according to time zone history) or as fixed offset like "GMT" (then of course no additional hour shift). By the way, the cited british website about greenwich mean time does unfortunately not enlighten the user about different historic tz data.

OTHER TIPS

When you are calling format(number) with a number it actually calling the Format.format(Object) and intern calling the SimpleDataFormat.format() with the following reference:

    if (obj instanceof Date) {  // deal with Date object pass in
        format((Date)obj, sb, delegate);
    }
    else if (obj instanceof Number) {  // deal with number pass in, 
        format(new Date(((Number)obj).longValue()), sb, delegate);
    }

And if you notice it actually send that number as longValue to the new Date() ...

So, it would be equivalent of you call as

System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date(0)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top