Java SimpleDateFormat: an hour wrong

Menno picture Menno · Jan 2, 2013 · Viewed 8.2k times · Source

I don't need a whole story to clarify my question, so I'll just show the code (which is a mere example). How come there is a difference in my result?

Code

long millis = 2305293L;
System.out.println(
    millis + "ms = " + 
    (millis / 1000) + "s = " + 
    (millis / 1000 / 60) + "m");
System.out.println(
    new SimpleDateFormat("HH:mm:ss").
    format(
        new Date(millis)
        )
    );

Output

2305293ms = 2305s = 38m
01:38:25

Answer

Peter Lawrey picture Peter Lawrey · Jan 2, 2013

If you are in London, or Paris, the timezone was GMT+1 on 1 Jan 1970.

For reasons @ARC explains in the comments, the UK used GMT+1 or UTC+1 from 18 Feb 1968 to 31 Oct 1971

is it possible for me to convert a long without any timezones interfering?

Set the TimeZone to be GMT.

long millis = 2305293L;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(new Date(millis)));

prints

00:38:25.293