Java ProgramsBasics & I/OConvert Seconds to Hours, Minutes and Seconds

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. 1totalSeconds holds 3665.
  2. 2totalSeconds / 3600 gives 1 whole hour, and totalSeconds % 3600 gives 65 leftover seconds.
  3. 365 / 60 gives 1 whole minute from those leftover seconds, and 65 % 60 gives 5 seconds still left over.
  4. 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

Related Programs