I have a time in milliseconds: 1618274313
.
When I convert it to time using this website: https://www.epochconverter.com/, I am getting 6:08:33 AM
.
But when I use SimpleDateFormat
, I am getting something different:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
System.out.println(sdf.format(new Date(1618274313)));
I am getting output as 23:01:14
.
What is the issue in my code?
In your example, you are using time 1618274313
and you are assuming that it is in milliseconds. However, when I entered the same time on https://www.epochconverter.com/, I got below results:
Please notice the site mentions: Assuming that this timestamp is in seconds
.
Now if we use that number multiplied by 1000
(1618274313000
) as the input so that the site considers it in milliseconds, we get below results:
Please notice the site now mentions: Assuming that this timestamp is in milliseconds
.
Now, when you will use 1618274313000
(correct time in milliseconds) in Java with SimpleDateFormat
, you should get your expected result (instead of 23:01:14
):
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
System.out.println(sdf.format(new Date(1618274313000)));