Skip to content
Advertisement

Issue Converting seconds to HH:MM:SS java

I have a long variable which represents the downtime of an application in seconds. I want to display the downtime as HH:mm:ss

Long downTime = 755; 
Date newD = new Date(downTime * 1000);

When passing the long variable to the Date I multiplied it 1000 to get the millisecond value. The newD variable evaluates to Thu Jan 01 01:12:35 GMT 1970

The value of newD is off by 1 hour, 755 seconds is = 00:12:35

It was my understanding that seconds * 1000 = milliseconds will evaluate to the correct answer. As I seen here

If I use Duration we get the right answer.

Duration d = Duration.ofSeconds(downTime);
PT12M35S

But the formatting is not as I want it.

Advertisement

Answer

LocalTime.MIN

LocalTime.MIN.plusSeconds( 755L ) 

Or,

LocalTime.MIN.plus( 
    Duration.ofSeconds( 755L ) 
)

CAVEAT: This is a hack, and I do not recommend it. Representing a span-of-time as a time-of-day is ambiguous and confusing.

By default, the LocalTime::toString method omits the trailing units if zero. To force all three parts (hours, minutes, seconds), use a DateTimeFormatter.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "HH:mm:ss" ) ;
String output = lt.format( f ) ;

See this code run live at IdeOne.com.

00:12:35

ISO 8601

I suggest, if possible, to train your users on the standard ISO 8601 format. This format is practical, clear, and unambiguous. The standard formats are used by default in the java.time classes for parsing/generating strings.

PT12M35S

Or generate a string spelling out the amount of time in prose.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement