How to Convert Milliseconds to "X Mins, X Seconds" in Java

How to convert Milliseconds to X mins, x seconds in Java?

Use the java.util.concurrent.TimeUnit class:

String.format("%d min, %d sec", 
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);

Note: TimeUnit is part of the Java 1.5 specification, but toMinutes was added as of Java 1.6.

To add a leading zero for values 0-9, just do:

String.format("%02d min, %02d sec", 
TimeUnit.MILLISECONDS.toMinutes(millis),
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);

If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations:

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);
//etc...

How to convert milliseconds to hh:mm:ss format?

You were really close:

String.format("%02d:%02d:%02d", 
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

You were converting hours to millisseconds using minutes instead of hours.

BTW, I like your use of the TimeUnit API :)

Here's some test code:

public static void main(String[] args) throws ParseException {
long millis = 3600000;
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
}

Output:

01:00:00

I realised that my code above can be greatly simplified by using a modulus division instead of subtraction:

String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));

Still using the TimeUnit API for all magic values, and gives exactly the same output.

convert milliseconds to seconds, minutes without rounding

Use floating point arithmetics on division:

(elapsedTimeMillis/1000.0)

and

(elapsedTimeMillis/(1000.0*60))

correspondingly.

In other words:

double seconds =  elapsedTimeMillis / 1000.0;
double minutes = (elapsedTimeMillis / (1000.0 * 60)) % 60;

How to convert milliseconds into hours and days?

The code below does the math you need and builds the resulting string:

private static final int SECOND = 1000;
private static final int MINUTE = 60 * SECOND;
private static final int HOUR = 60 * MINUTE;
private static final int DAY = 24 * HOUR;

// TODO: this is the value in ms
long ms = 10304004543l;
StringBuffer text = new StringBuffer("");
if (ms > DAY) {
text.append(ms / DAY).append(" days ");
ms %= DAY;
}
if (ms > HOUR) {
text.append(ms / HOUR).append(" hours ");
ms %= HOUR;
}
if (ms > MINUTE) {
text.append(ms / MINUTE).append(" minutes ");
ms %= MINUTE;
}
if (ms > SECOND) {
text.append(ms / SECOND).append(" seconds ");
ms %= SECOND;
}
text.append(ms + " ms");
System.out.println(text.toString());

How to convert milliseconds to seconds with precision

Surely you just need:

double seconds = milliseconds / 1000.0;

There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0 (as a double literal) forces. (I'm assuming your milliseconds value is an integer of some form.)

Note that as usual with double, you may not be able to represent the result exactly. Consider using BigDecimal if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double is probably appropriate, but...)

How to convert milliseconds to mm:ss:ms format?

From System.currentTimeMillis():

Returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

So what you see in your output is the Hh:mm:ss portion of the time taken between 1970-01-01T00:00:00 up until now.

What you actually want is the taken time i.e the difference between start and end of your time measurement.

val start = System.currentTimeMillis()

// do your processing

val end = System.currentTimeMillis()
val time = String.format("%1$tM min. %1$tS sec. %1$tL ms.", end - start)

This should give you an appropriate output.


As noted in the comments weird stuff happens in some timezones. And String.format() seems to be quite unconfigurable (at least I didn't find anything).

If you really want to be on the safe side, you can use the answer suggested by @SergeyAfinogenov, but with some minor tweaks:

val minutes = duration.getSeconds() / 60
val seconds = duration.getSeconds() - minutes * 60
val millis = duration.getNano() / 1_000_000
val time = String.format("%d min. %d sec. %d ms.%n", minutes, seconds, millis)

This effectively manually calculates the different parts (minutes, seconds, millis) from the Duration and then formats them accordingly.

How do I convert milliseconds to days, hour, minutes

Java 9 or later

Let’s first declare a couple of helpful constants.

private static final int TICKS_PER_SECOND = 20;
public static final Duration ONE_TICK = Duration.ofSeconds(1).dividedBy(TICKS_PER_SECOND);

Now do:

    int ticks = player.getStatistic(Statistic.PLAY_ONE_TICK);
Duration plpTime = ONE_TICK.multipliedBy(ticks);
String result1 = String.format(Locale.ENGLISH, "%02d days %02d hours and %02d minutes",
plpTime.toDays(), plpTime.toHoursPart(), plpTime.toMinutesPart());

System.out.println(result1);

This prints a string like

00 days 17 hours and 08 minutes

Possibly the number of ticks per second (20) is already declared as a constant somewhere in Bukkit, I don’t know. If it is, take that one rather declaring your own.

Java 6, 7 or 8

The toXxxPart methods I used were introduced in Java 9. Without them we need to calculate the individual parts like this:

    long days = plpTime.toDays();
plpTime = plpTime.minusDays(days);
long hours = plpTime.toHours();
plpTime = plpTime.minusHours(hours);
long minutes = plpTime.toMinutes();
String result1 = String.format(Locale.ENGLISH, "%02d days %02d hours and %02d minutes",
days, hours, minutes);

The result is the same as above.

Question: How can that work in Java 6 or 7?

The Duration class that I am using is part of java.time, the modern Java date and time API

  • In Java 8 and later and on newer Android devices (from API level 26, I’m told) java.time comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

What went wrong in your code?

Why the hours seem to start at 1 (not 0): It’s your time zone. When you create a Date from your milliseconds, you get the point in time that many milliseconds after the epoch defined as 00:00 UTC on Jan 1, 1970 (which conceptually is quite misleading when the question was when a player joined). If your time zone was 1 hour ahead of UTC in the winter of 1970 (like Central European time, for example), it was already 1 o’clock at the epoch, so the hours count from there.

And since it was January 1, the day is given as 1, of course. Curiously, if you had been in a time zone west of GMT (America/Los_Angeles to give just one example), the date would still have been December 31, 1969 in the first hours after the epoch, so the newly joined player might appear to have been there for 31 days, 16 hours and 00 minutes, for example.

Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

From milliseconds to hour, minutes, seconds and milliseconds

Here is how I would do it in Java:

int seconds = (int) (milliseconds / 1000) % 60 ;
int minutes = (int) ((milliseconds / (1000*60)) % 60);
int hours = (int) ((milliseconds / (1000*60*60)) % 24);


Related Topics



Leave a reply



Submit