I am looking for a time utils for java where I can give a time in seconds or in milis and it'll return with methods for for example getSeconds
and getMinutes
so I can easily format the text to look like Remaining 1 day 2 hours 3 minutes and 4 seconds
.
Does anyone know any?
Asked
Active
Viewed 55 times
-1

Ole V.V.
- 81,772
- 15
- 137
- 161

User12322341232142
- 93
- 1
- 8
-
1Have you done any research? – Roger Gustavsson Sep 27 '19 at 12:28
-
1Maybe `java.time.Duration` – greg-449 Sep 27 '19 at 12:40
-
If you only need days max (ie, not months), then this just requires few divisions, no need for a library for that – Bentaye Sep 27 '19 at 12:59
-
Possible duplicate of [How to format a duration in java? (e.g format H:MM:SS)](https://stackoverflow.com/questions/266825/how-to-format-a-duration-in-java-e-g-format-hmmss) (you can trivially adapt the answers from there to give you `1 day 2 hours 3 minutes and 4 seconds`). – Ole V.V. Sep 27 '19 at 19:15
1 Answers
0
There are 60 seconds in a minute, 60 minutes in an hour and 24 hours in a day so:
private static final int SECONDS_IN_MINUTE = 60;
private static final int SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
private static final int SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR;
Then you just need to keep on dividing:
class RemainingTime {
private static final int SECONDS_IN_MINUTE = 60;
private static final int SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
private static final int SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR;
private int totalSeconds, days, hours, minutes, seconds;
public RemainingTime(int totalSeconds) {
this.totalSeconds = totalSeconds;
init();
}
private void init() {
int remainingSeconds = totalSeconds;
days = remainingSeconds / SECONDS_IN_DAY;
remainingSeconds -= days * SECONDS_IN_DAY;
hours = remainingSeconds / SECONDS_IN_HOUR;
remainingSeconds -= hours * SECONDS_IN_HOUR;
minutes = remainingSeconds / SECONDS_IN_MINUTE;
remainingSeconds -= minutes * SECONDS_IN_MINUTE;
seconds = remainingSeconds;
}
public int getDays() { return days; }
public int getHours() { return hours; }
public int getMinutes() { return minutes; }
public int getSeconds() { return seconds; }
}
You use it like this:
RemainingTime rt = new RemainingTime(274119);
System.out.println(String.format(
"Remaining %s day(s), %s hour(s), %s minute(s) and %s second(s)",
rt.getDays(), rt.getHours(), rt.getMinutes(), rt.getSeconds()));
Outputs:
Remaining 3 day(s), 4 hour(s), 8 minute(s) and 39 second(s)

Bentaye
- 9,403
- 5
- 32
- 45