I want to convert seconds into HH:mm:ss
time format, so:
seconds = 3754
result = 10:25:40
I know about the conventional approach of dividing it by 3600 to get hours an so on, but was wondering if I can achieve this through Java API?
Using java.util.Calendar:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 37540);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(calendar.getTime()));
In my own library Time4J (v1.2) a pattern-based solution ready for Java 6 and later looks like:
Duration<?> dur =
Duration.of(37540, ClockUnit.SECONDS).with(Duration.STD_CLOCK_PERIOD);
String s = Duration.Formatter.ofPattern("hh:mm:ss").format(dur);
System.out.println(s); // 10:25:40
In Joda-Time following code is possible using a builder approach:
PeriodFormatter f =
new PeriodFormatterBuilder().appendHours().appendLiteral(":").appendMinutes()
.appendLiteral(":").appendSeconds().toFormatter();
System.out.println("Joda-Time: " + f.print(new Period(37540 * 1000))); // 10:25:40
My previous posted solution was a field-based-workaround (using the field SECOND_OF_DAY) which has a serious disadvantage, namely to be limited to seconds less than 86400 (day-length). The accepted answer using old Calendar-code suffers from this bug, too, so it is not a real solution. In Java-8 (containing a new time library - JSR-310) there is also no solution available because it still misses the possibility to format durations. Sample outputs of the different proposals:
input = 337540 seconds (almost 4 days)
code of accepted solution => 21:45:40 (WRONG!!!)
Time4J-v1.2 => 93:45:40
Joda-Time => 93:45:40
Conclusion, use an external library for solving your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With