java计算总小时数和分钟数

时间:2015-01-11 02:55:15

标签: java

我有这些时间

8:00 8:30 8:40和10:00

我想做的是总结它们

8:00 + 8:30 + 8:40 + 10:00 = 35:10

是否可以显示或打印超过24小时的时间?

它返回0

private void btnCalculateActionPerformed(java.awt.event.ActionEvent evt) {                                             
    String[] timeInAM;
    String[] timeOutAM;
    String[] timeInPM;
    String[] timeOutPM;
    Calendar time;
    for(int i=0;i<tblWorkPeriod.getRowCount();i++)
    {
        timeInAM=tblWorkPeriod.getValueAt(i, 1).toString().split(":");
        timeOutAM=tblWorkPeriod.getValueAt(i, 2).toString().split(":");
        timeInPM=tblWorkPeriod.getValueAt(i, 3).toString().split(":");
        timeOutPM=tblWorkPeriod.getValueAt(i, 4).toString().split(":");
        LocalTime inAM=new LocalTime(Integer.valueOf(timeInAM[0]),Integer.valueOf(timeInAM[1]));
        LocalTime outAM=new LocalTime(Integer.valueOf(timeOutAM[0]),Integer.valueOf(timeOutAM[1]));
        LocalTime inPM=new LocalTime(Integer.valueOf(timeInPM[0]),Integer.valueOf(timeInPM[1]));
        LocalTime outPM=new LocalTime(Integer.valueOf(timeOutPM[0]),Integer.valueOf(timeOutPM[1]));

        LocalTime intervalAM=outAM.minusHours(inAM.getHourOfDay()).minusMinutes(inAM.getMinuteOfHour());
        LocalTime intervalPM=outPM.minusHours(inPM.getHourOfDay()).minusMinutes(inPM.getMinuteOfHour());
        LocalTime total = intervalAM.plusHours(intervalPM.getHourOfDay()).plusMinutes(intervalPM.getMinuteOfHour());

        tblWorkPeriod.setValueAt(total.toString().substring(0, total.toString().lastIndexOf(":")),i,5);
    }
    LocalTime total=new LocalTime(0,0);
    for(int i=0;i<tblWorkPeriod.getRowCount()-1;i++)
    {
        String[] strSubtotal=tblWorkPeriod.getValueAt(i, 5).toString().split(":");
        LocalTime subtotal=new LocalTime(Integer.valueOf(strSubtotal[0]),Integer.valueOf(strSubtotal[1]));
        total=total.plusHours(subtotal.getHourOfDay()).plusMinutes(subtotal.getMinuteOfHour());
    }


}   

2 个答案:

答案 0 :(得分:2)

如果String time1 = "8:00"String time2 = "9:00"然后通过一个总分钟的方法传递它们。然后将它们一起添加并解析最终结果;)

public static void main(String[] args) {
    String time1 = "8:00";
    String time2 = "9:00";
    int t1 = getTotalMinutes(time1);
    int t2 = getTotalMinutes(time2);
    int total = t1 + t2;
    String result = getResult(total);
    System.out.println(result);
}

public static int getTotalMinutes(String time) {
    String[] t = time.split(":");
    return Integer.valueOf(t[0]) * 60 + Integer.valueOf(t[1]);
}

public static String getResult(int total) {
    int minutes = total % 60;
    int hours = ((total - minutes) / 60) % 24;
    return String.format("%02d:%02d", hours, minutes);
}

答案 1 :(得分:0)

拆分它们并将它们放入arraylist中。这是一个更好的阵列解决方案,因为你可以扩展它