java convert seconds into hhmmss

Posted in :


在 database 裡有 startTime, endTime 的 2個欄位, 內容值相減後是秒數, 希望可以變成 HH:MM:SS 格式.


Using the old java date api (not recommended, see comments):

int sec = .... //
Date d = new Date(sec * 1000L);
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); // HH for 0-23
String time = df.format(d);

See also SimpleDateFormat.

Note: as per comments, if the number of seconds exceeds the number of seconds in a day (86400) that won’t work as expected. In that case a different approach must be taken.

EDIT: If you’re using JDK 8 you can write:

int sec = ...
Duration duration = Duration.ofSeconds(sec);

This duration object better represents what you’re talking about. I am trying to find out how to format it as you want to but I have had no luck so far.

EDIT 2: prior to JDK 8 you can use the Joda API:

int sec = ...
Period period = new Period(sec * 1000L);
String time = PeriodFormat.getDefault().print(period); // you can customize the format if this one doesn't cut it

That’s probably the most elegant solution. See also this.

EDIT 3: As per comments, I explicitly added the time zone.

上面解法, 會遇到超過24小時就掛掉的問題.


long input = 1209660L;
long days = input / 86400L;
long hours = (input % 86400L) / 3600L;
long minutes = (input % 86400L % 3600L) / 60L;
long seconds = input % 86400L % 3600L % 60L;
return String.format("%s %s  %s  %s ",
  days!=0?days+" day(s)" :"",
  hours!=0?hours+" hr(s)":"",
  minutes!=0?minutes+" min(s)":"",
  seconds!=0?seconds+" sec(s)":"");


發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *