在java中一起添加时间

时间:2013-06-25 06:52:57

标签: java datetime time

我从数据库获取时间行如下

TimeWorked
09:05:25
09:30:15
10:15:01
08:19:49
09:17:40

现在我想在java中总结一下时间来获得 46:28:10 。我尝试了使用Calendar类的东西,但它没有用。如何在java中总结这些时间

感谢回复

3 个答案:

答案 0 :(得分:3)

如果你的项目可能,我建议你使用JodaTime和Duration类。它比使用标准Java Calendar / Date API容易得多。

这是使用Period类的另一个例子:

PeriodFormatter hoursMinutesSecondsFormatter = 
     new PeriodFormatterBuilder().appendHours().appendSeparator(":")
            .appendMinutes().appendSeparator(":").appendSeconds().toFormatter();
Period period1 = hoursMinutesSecondsFormatter.parseMutablePeriod("09:05:25").toPeriod();
Period period2 = hoursMinutesSecondsFormatter.parseMutablePeriod("09:30:15").toPeriod();
System.out.println(period1.plus(period2).toString(hoursMinutesSecondsFormatter));

打印:18:35:40

答案 1 :(得分:2)

开始你的循环行获取循环中的每一行并继续

int hour = 0;
int minute = 0;

for(<your row loop>) {
    String[] rowtime= row[i].split(":");
    hour += Integer.parseInt(rowtime[0]);
    minute += Integer.parseInt(rowtime[1]);
}

hour += minute / 60;
minute %= 60;

String result = hour + ":" + minute

答案 2 :(得分:1)

String[] timeWorked = {"09:05:25", "09:30:15"}

int hours = 0;
int minutes = 0;
int seconds = 0;

for(int i = 0; i < timeWorked.length; i++) {
    hours += Integer.parseInt(timeWorked.split(":")[0]);
    minutes += Integer.parseInt(timeWorked.split(":")[1]);
    seconds += Integer.parseInt(timeWorked.split(":")[2]);
}

// Now you have your hours minutes and seconds all added up and all you have to do is do some math similar to what shreyansh jogi said to calculate in hours minutes and seconds.

不要忘记捕获可能从parseInt抛出的NumberFormatExceptions