Java: SimpleDateFormat adds 1 to the day and hour (time interval)

I am trying to output "900,000 milliseconds" in the format "days: hours: minutes: seconds", and I'm using this code right now:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:HH:mm:ss"); String formatted = simpleDateFormat.format(900000) 

900,000 milliseconds should be 15 minutes so I want it back

 00:00:15:00 

or something like that ...

But for some reason it returns

 01:01:15:00 

Can someone tell me why and how to fix it?

I thought he needed to do something with time zones, but it added 1 to the number of days ...?

Thanks in advance!

+4
source share
4 answers

You are wrong about this using SimpleDateFormat

SimpleDateFormat used to get a DATE instance, not counting the time

You must use TimeUnit

Here is an example

  public static void main(String[] args) throws Exception { long millis = 900000; String s = String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes(millis), TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); System.out.println(s); } 

It will help you

15 min, 0 sec

Just format your content and add days and hours ...

+8
source

Day 01, because it costs January 01. Hour 01 may be associated with your time zone. Try the following:

 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd:HH:mm:ss"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String formatted = simpleDateFormat.format(900000); 
+10
source

The 900,000 value passed to SimpleDateFormat is a point in time ... 15 minutes January 1, 1970, 00:00:00 GMT or:

January 1, 1970 00:15:00 GMT

At this date and time in 1970, in your time zone, the day is 1 and the hour is 1.

+7
source

The answer is correct. The SimpleDate.format (900000) instruction displays the time elapsed after 900,000 ms, which will be 15 minutes in the first hour

0
source

Source: https://habr.com/ru/post/1438663/


All Articles