Exercise:
Write a Java Program to convert milliseconds to minutes and seconds.
1.Convert to minutes and seconds individually
Click Here to View the Solution!
import java.util.concurrent.TimeUnit;
public class MillisecondsConcertor {
public static void main(String[] args) {
long milliseconds = 1300000;
// calculates minutes= (milliseconds / 1000) / 60;
long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
// calculates seconds = (milliseconds / 1000);
long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds);
System.out.format("%d Milliseconds = %d minutes\n", milliseconds, minutes );
System.out.println("Or");
System.out.format("%d Milliseconds = %d seconds", milliseconds, seconds );
}
}
Click Here to View the Output!
1300000 Milliseconds = 21 minutes Or 1300000 Milliseconds = 1300 seconds
Click Here to View the Explanation!
- This program is used to convert the milliseconds in time into minutes and seconds separately.
- Initially, the milliseconds are set in the program as
milliseconds = 130000
. - The program uses a
TimeUnit
class of the java.util.concurrent package that provides two methods which are used to convert milliseconds to minutes and seconds. - The program initializes a minutes variable which holds the
.toMinutes()
method of theTimeUnit
class that converts millisecond to minutes. And a seconds variable which holds the.toSeconds()
method that converts milliseconds to seconds. - Finally, both the conversion the displayed individually.
2.Convert to minutes and seconds
Click Here to View the Solution!
public
class MillisecondsConvertor {
public static void main(String[] args) {
long milliseconds =
1450000;
long minutes = (milliseconds /
1000) /
60;
long seconds = (milliseconds /
1000) %
60;
System.out.format(
"%d Milliseconds = %d minutes and %d seconds.", milliseconds, minutes, seconds);
}
}
Click Here to View the Output!
1450000 Milliseconds = 24 minutes and 10 seconds.
Click Here to View the Explanation!
- This program is used to convert the milliseconds into minutes and seconds by using simple math and displaying them together.
- Initially,
milliseconds = 145000
. - The program uses two simple formulas for both minutes and seconds conversions. For minutes, the formula used is (milliseconds / 1000) / 60. Which is dividing the milliseconds by the number of seconds (1000) and then dividing by the number of minutes (60). This will the give the number of minutes in
145000
milliseconds. - The second formula will calculate the remaining number of seconds in
145000
milliseconds. The formula (milliseconds / 1000) % 60, which is dividing the milliseconds by the number of seconds (1000) and then getting the remainder by dividing with the number of minutes (60). This will the give the remaining number of seconds in 145000 milliseconds besides the previously calculated 24 minutes. - Finally, the conversion will be displayed as
24 minutes and 10 seconds.