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

I want to convert seconds to time format HH:mm:ss, therefore:

seconds = 3754 
result  = 10:25:40 

I know about the usual approach to dividing it by 3600 to get hours and so on, but wondered if I can achieve this through the Java API?

+4
source share
3 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()));
+10
source

Updated and fixed my answer:

In my own Time4J library (v1.2), a template-based solution, ready for Java 6 and later, looks like this:

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, the following code is possible using the 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

( SECOND_OF_DAY), , 86400 ( ). , . Java-8 ( - JSR-310) - . :

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

, .

+1

LocalTime

Java, Java, . LocalTime . , .

LocalTime lt = LocalTime.ofSecondOfDay( 3_754L );

, .

lt.toString(): 01:02:34

. . .

-- Duration.

Duration d = Duration.ofSeconds( 3_754L );

d.toString(): PT1H2M34S

, ISO 8601 PnYnMnDTnHnMnS, P T years-month-days --. , , , " , ".


java.time

java.time Java 8 . legacy -, java.util.Date, .Calendar java.text.SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru . JSR 310.

java.time?

The ThreeTen-Extra project extends java.time with additional classes. This project is proof of possible future additions to java.time. Here you can find useful classes, such as Interval, YearWeek, YearQuarterand longer .

0
source

All Articles