In many applications, it is common to work with time durations represented in seconds. For better user experience, we often need to convert these time durations into a more human-readable format, such as days, hours, minutes, and seconds.

In the article, we will see how to convert seconds to days, hours, minutes, and seconds in Java.

Using the java.time package

The java.time package provides powerful date and time APIs, including the Duration class, which is ideal for representing time durations. Using this, we can easily convert seconds to days, hours, minutes, and seconds and perform simple operations.

import java.time.*;

Convert seconds to the duration

Next, we need to convert the number of seconds to a Duration object. We can use the Duration.ofSeconds() method for this purpose:

long seconds = 86450; // Example: 86450 seconds represents 1 day, 0 hours, 0 minutes, and 50 seconds
Duration duration = Duration.ofSeconds(seconds);

Get Days, Hours, Minutes, and Seconds

With the Duration object, we can easily extract the number of days, hours, minutes, and seconds using various methods provided by the class:

long days = duration.toDays();
long hours = duration.toHours() % 24;
long minutes = duration.toMinutes() % 60;
long remainingSeconds = duration.getSeconds() % 60;

In the above example, we use toDays() to get the total number of days, toHours() % 24 to get the remaining hours after subtracting the days, toMinutes() % 60 to get the remaining minutes after subtracting the days and hours, and getSeconds() % 60 to get the remaining seconds after subtracting the days, hours, and minutes.

Following is the sample output when we run the above code with the sample output i.e. 86450

Days: 1, Hours: 0, Minutes: 0, Seconds: 50

Categorized in:

Tagged in: