我有以下方法来计算时间:
public static String sumTime(String date1, String date2) throws ParseException {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
Date d1 = formatter.parse(date1);
Date d2 = formatter.parse(date2);
calendar.setTime(d2);
d1 = DateUtils.addHours(d1, calendar.get(Calendar.HOUR_OF_DAY));
d1 = DateUtils.addMinutes(d1, calendar.get(Calendar.MINUTE));
d1 = DateUtils.addSeconds(d1, calendar.get(Calendar.SECOND));
d1 = DateUtils.addMilliseconds(d1, calendar.get(Calendar.MILLISECOND));
return formatter.format(d1);
}
DateUtils 来自 Apache Commons Lang 3
除非总和大于 24 小时,否则它对我想要的效果非常好。
例如:
String time = "00:00:00.000";
try {
for (int i = 0; i < 24; i++) {
time = sumTime(time, "01:00:00.123");
}
System.out.println(time);
} catch (ParseException e) {
e.printStackTrace();
}
结果是:
00:00:02.952
但这就是我希望的样子:
24:00:02.952
有什么(简单的)方法可以做到这一点吗?
我不介意使用不同的库/方法,只要我得到正确的结果。
请记住,时间总是从 00:00:00.000 开始;
最佳答案
您是否考虑过用天来表示每组 24 小时?您可以在 sumTime 方法中添加一些内容,并让它添加天数。 SimpleDateFormater 可以使用几天,也许这会有所帮助:
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
关于java - 过去 24 小时的总计时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11354756/