LearnFrenzy
Sign in Take a free test

Java Basics, Syntax and Data Types · Java Basics Programs · Question 5

Convert seconds to days, hours, minutes and seconds in Java Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Read a number of seconds (possibly very large) and print it as days, hours, minutes and seconds, using long arithmetic and / and %.

Solution
Main.java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextLong()) {
            long total = in.nextLong();
            long days = total / 86_400;
            long hours = total % 86_400 / 3_600;
            long minutes = total % 3_600 / 60;
            long seconds = total % 60;
            System.out.printf("%,d s = %dd %02dh %02dm %02ds%n", total, days, hours, minutes, seconds);
        }
    }
}

Output Verified by compiling and running

59 s = 0d 00h 00m 59s
3,725 s = 0d 01h 02m 05s
100,000 s = 1d 03h 46m 40s
3,000,000,000 s = 34722d 05h 20m 00s

3 billion does not fit in an int, so long is used throughout. % 86_400 / 3_600 extracts the hours within a day.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links