【发布时间】:2015-04-26 10:33:12
【问题描述】:
我正在处理一个管理任务的基本项目。工作日为 8:00 至 17:00。任务具有开始时间和预计持续时间。此预计持续时间以 分钟 为单位。我要计算结束时间。
我已经想出了如何在开始时间上添加天数,但它远非精确。我将估计的持续时间除以 540(= 9 小时),所以我知道大约有多少天。但我希望能够准确计算结束日期。
我不能只是不能将分钟添加到日历中,因为日历使用 24 小时制而不是 9 小时制。例如,如果开始时间是 2015-04-26 16:00:00.0,我加上 180 分钟(3 小时),那么结束时间就是 2015-04-27 10:00:00.0。这将如何完成?这是我目前所拥有的:
public TimeSpan calculateEstimatedDuration() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
//divide by 540 because there are 9 hours in a work day
long workingDays = Math.round((this.getEstimatedDuration()/540));
//convert to calendar to add the estimated working days to the start date
Date startDate = this.getPlannedStartTime();
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
cal.add(Calendar.DATE,(int) workingDays);
String endTime = format.format(cal.getTime());
Date PlannedEndTime = format.parse(endTime);
return new TimeSpan(this.getPlannedStartTime(),PlannedEndTime);
}
【问题讨论】:
-
答案取决于本地化,因为您需要照顾周末以外的空闲时间。你关心假期吗?
-
@Yoda 不,我不在乎周末或节假日。
-
cal.add(Calendar.MINUTE,(this.getEstimatedDuration()%540));是你想要的吗? -
我给了this Answer 一个类似的问题,使用 java.time 的工作源代码可能有用。在那个代码中,我每天都在移动,到第二天的第一刻。您可以通过移动到工作日结束来更改该逻辑(然后跳到下一个工作日的开始)。