Convert Seconds to Hours, Minutes and Seconds in Java
intermediate· Basics & I/O · Conversions
Problem
The same divide-and-remainder technique used for days-to-years works here too, just with 3600 seconds per hour and 60 seconds per minute instead of 365 and 30.
Given a total number of seconds, express it as a number of hours, minutes, and remaining seconds.
Input
totalSeconds = 3665
Output
1 hours, 1 minutes, 5 seconds
Java Program
Java
public class ConvertSecondsToHoursMinutesAndSeconds {
public static void main(String[] args) {
int totalSeconds = 3665;
int hours = totalSeconds / 3600;
int remainingAfterHours = totalSeconds % 3600;
int minutes = remainingAfterHours / 60;
int seconds = remainingAfterHours % 60;
System.out.println(hours + " hours, " + minutes + " minutes, " + seconds + " seconds");
}
}Output
1 hours, 1 minutes, 5 seconds
Core Logic
Dividing by 3600 peels off whole hours, then dividing what's left by 60 peels off whole minutes, leaving only seconds behind.
How It Works
- 1
totalSecondsholds3665. - 2
totalSeconds / 3600gives1whole hour, andtotalSeconds % 3600gives65leftover seconds. - 3
65 / 60gives1whole minute from those leftover seconds, and65 % 60gives5seconds still left over. - 4The three results are printed together as
hours, minutes, seconds.
For
totalSeconds = 3665: 3665 / 3600 = 1 hour with 65 seconds left, then 65 / 60 = 1 minute with 5 seconds left.💡
Key Point: 3600 and 60 are just the number of seconds in an hour and a minute — the exact same division-and-remainder pattern would work for any pair of nested units, not just time.
Key Concepts
intinteger divisionmodulo