I want to change milliseconds to X minutes X seconds in Java.

Asked 2 years ago, Updated 2 years ago, 70 views

I want to record the time when the user starts my program using System.currentTimeMillis(). I want to express the recorded time in XX hours XX minutes, XX seconds or XX minutes, XX seconds anyway, how do I do it?

Do not paste the entire source code. Attach the source code only if it helps you understand the problem.

java time

2022-09-22 22:33

1 Answers

Write java.util.concurrent.TimeUnit as below.

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

It's 01, 02 when you print out a number in two digits

String.format("%02d min, %02d sec", 
    TimeUnit.MILLISECONDS.toMinutes(millis),
    TimeUnit.MILLISECONDS.toSeconds(millis) - 
    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))
);
int seconds = (int) (milliseconds / 1000) % 60 ; //sec
int minutes = (int) ((milliseconds / (1000×60)) %60); //min
int hours = (int) ((milliseconds / (1000×60×60)) %24);//hour

If you want to save time, you can do this


2022-09-22 22:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.