Java Program to convert time millsecond to min and seconds.
Objective
Write a Java program to convert milliseconds into Minutes and Seconds.
Algorithm / Approach
- Read an integer representing milliseconds from the user.
- Divide by 1000 to convert to total seconds.
- Divide total seconds by 60 to get total minutes.
- Use the modulo operator (
% 60) on the total seconds to get the remaining leftover seconds. - Format the output as
MM:SSusingString.format("%02d : %02d", tm, ts).
Test.java
import java.util.*;
class Test {
public static void main(String [] ar){
Scanner sc = new Scanner(System.in);
System.out.print("Time in mills:");
int tms = sc.nextInt();
int ts = tms/1000;
int tm = ts/60;
ts = ts%60;
String ft;
ft = String.format("%02d : %02d",tm,ts);
System.out.println(ft);
}
}
Expected Output
Time in mills: 213312 03:33
Explanation of the Program
- This is a classic math problem often used in game development or media players to convert a raw timestamp into a human-readable digital clock format.
- The format flag
%02densures that single-digit numbers are padded with a leading zero (e.g., 3 minutes becomes "03").
Complexity
Time Complexity
O(1)
Space Complexity
O(1)