Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get time in hh:mm:ss from seconds in Java

Tags:

java

time

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?

like image 507
user523956 Avatar asked Feb 24 '14 12:02

user523956


2 Answers

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()));
like image 192
david a. Avatar answered Sep 19 '22 23:09

david a.


Updated and corrected my answer:

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.

like image 44
Meno Hochschild Avatar answered Sep 17 '22 23:09

Meno Hochschild