Java Program to input time in millisecond and show in minuts and second.
Objective
Write a Java program to convert milliseconds into minutes and seconds.
Algorithm / Approach
- Take time in milliseconds as input.
- Divide by 1000 to get total seconds.
- Divide total seconds by 60 to get minutes.
- Use the modulo operator
% 60on total seconds to get the remaining seconds. - Print the result in MM:SS format.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Time in millis:");
int tms = s.nextInt();
int ts = tms/1000;
int tm = ts/60;
ts = ts%60;
System.out.print("Time- "+tm+":"+ts);
}
}
Expected Output
Enter Time in millis:75000 Time- 1:15
Explanation of the Program
- The total milliseconds
tmsare input by the user. - Total seconds
tsare calculated by dividingtmsby 1000. - Total minutes
tmare found by dividing the total seconds by 60. - The remaining seconds are calculated using the modulo operator
ts % 60.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Using division
/ 60for seconds instead of modulo% 60.