Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SimpleDateFormat: an hour wrong

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
like image 280
Menno Avatar asked Jan 02 '13 15:01

Menno


People also ask

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

Is SimpleDateFormat thread-safe True or false?

SimpleDateFormat is not thread-safe in any JDK version, nor will it be as Sun have closed the bug/RFE.

Is SimpleDateFormat thread-safe in java?

Java's SimpleDateFormat is not thread-safe, Use carefully in multi-threaded environments. SimpleDateFormat is used to format and parse dates in Java. You can create an instance of SimpleDateFormat with a date-time pattern like yyyy-MM-dd HH:mm:ss , and then use that instance to format and parse dates to/from string.

What is the difference between DateTimeFormatter and SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.


1 Answers

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
like image 191
Peter Lawrey Avatar answered Sep 23 '22 02:09

Peter Lawrey