毫秒到小时(超过24)

时间:2017-03-07 18:28:50

标签: java time

我有一个总结所有小时数(转换为毫秒)的系统,如果该小时超过24小时(例如26小时),它将返回02:00:00而不是26:00:00

totH = parser.parse(totalH);
totHTotal += totH.getTime(); // assume totHTotal gets 93600000.
totalHours = parser.format(new Date(totHTotal));
System.out.println(totalHours); // this will output 02:00:00 but I want this to output 26:00:00.

有人可以帮助我,谢谢你。

1 个答案:

答案 0 :(得分:0)

您可以使用Duration或进行算术。

1小时:3 600 000ms
1分钟:60 000ms
1秒:1 000ms

您可以在此处运行:https://repl.it/GLLH/9

import java.time.Duration;
class Main {
  public static void main(String[] args) {
    System.out.println("Using math");
    long millsMath = 93631000;

    long hoursMath = millsMath / 3600000;
    long minutesMath = (millsMath % 3600000) / 60000;
    long secondsMath = (millsMath % 60000) / 1000;

    String outMath = String.format("%02d:%02d:%02d",hoursMath, minutesMath, secondsMath);
    System.out.println(outMath);



    System.out.println("\nUsing Duration");
    Duration dur = Duration.ofMillis(93631000);

    long hoursDur   = dur.toHours();
    long minutesDur = dur.minusHours(hoursDur).toMinutes();
    long secondsDur = dur.minusHours(hoursDur).minusMinutes(minutesDur).getSeconds();

    String outDur = String.format("%02d:%02d:%02d", hoursDur, minutesDur, secondsDur);

    System.out.println(outDur);
  }
}

输出:

Using math
26:00:31

Using Duration
26:00:31