Issue Converting seconds to HH:MM:SS java

孤街醉人 提交于 2019-12-25 01:45:18

问题


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.


回答1:


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.




回答2:


Check if you can use this:

long millis = 755000;
String hms = String.format("%02d:%02d:%02d", 
    TimeUnit.MILLISECONDS.toHours(millis),
    TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
    TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
System.out.println(hms);


来源:https://stackoverflow.com/questions/46113091/issue-converting-seconds-to-hhmmss-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!