我有四个约会,我想得到总数。



timeInAM = 9:00

timeOutAM = 12:00

timeInPM = 13:00

timeOutPM = 18:00

我想将total=(timeOutAM-timeInAM)+(timeOutPM-timeInPM)设置为total = 8:00

却给我'16:00:00'

这是我所做的:
日期

SimpleDateFormat tf24=new SimpleDateFormat("HH:mm");
Date timeInAM=new Date();
Date timeOutAM=new Date();
Date timeInPM=new Date();
Date timeOutPM=new Date();
long total;

timeInAM=tf24.parse(tblWorkPeriod.getValueAt(i, 1).toString());
timeOutAM=tf24.parse(tblWorkPeriod.getValueAt(i, 2).toString());
timeInPM=tf24.parse(tblWorkPeriod.getValueAt(i, 3).toString());
timeOutPM=tf24.parse(tblWorkPeriod.getValueAt(i, 4).toString());
total=(timeOutAM.getTime()-timeInAM.getTime())+(timeOutPM.getTime()-timeInPM.getTime());
System.out.println(tf24.format(new Date(total)));


日历

Calendar timeInAM=Calendar.getInstance();
Calendar timeOutAM=Calendar.getInstance();
Calendar timeInPM=Calendar.getInstance();
Calendar timeOutPM=Calendar.getInstance();
Calendar total=Calendar.getInstance();

SimpleDateFormat tf24=new SimpleDateFormat("HH:mm");

timeInAM.setTime(tf24.parse(tblWorkPeriod.getValueAt(i, 1).toString()));
timeOutAM.setTime(tf24.parse(tblWorkPeriod.getValueAt(i, 2).toString()));
timeInPM.setTime(tf24.parse(tblWorkPeriod.getValueAt(i, 3).toString()));
timeOutPM.setTime(tf24.parse(tblWorkPeriod.getValueAt(i, 4).toString()));
long sum=(timeOutAM.getTimeInMillis()-timeInAM.getTimeInMillis())+(timeOutPM.getTimeInMillis()-timeInPM.getTimeInMillis());
total.setTimeInMillis(sum);
System.out.println("total : "+tf24.format(total.getTime()));

最佳答案

您可以尝试使用JodaTime库(如果可以使用其他库)。通过以下操作,您可以通过调用LocalTime::minusHours和类似命令来实现所需的功能:

LocalTime timeInAM=new LocalTime(hourOfDay, minuteOfHour);
LocalTime timeOutAM=new LocalTime(hourOfDay, minuteOfHour);
LocalTime timeInPM=new LocalTime(hourOfDay, minuteOfHour);
LocalTime timeOutPM=new LocalTime(hourOfDay, minuteOfHour);

LocalTime amInterval = timeOutAM.minusHours(timeInAM.getHourOfDay()).minusMinutes(timeInAM.getMinuteOfHour());
LocalTime pmInterval = timeOutPM.minusHours(timeInPM.getHourOfDay()).minusMinutes(timeInPM.getMinuteOfHour());

LocalTime total = pmInterval.plusHours(amInterval.getHourOfDay()).plusMinutes(amInterval.getMinuteOfHour());


使用适当的DateTimeFormatter解析/打印LocalTime中的日期。

关于java - Java时间的加减法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27879195/

10-11 13:58