我正在开发一个管理任务的基本项目。工作日为 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);
}
最佳答案
我找到了使用模运算符的解决方案,解释在评论中:
public TimeSpan addEstimatedToTime(Date time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
//first we get the days
long workingDays = this.getEstimatedDuration() / 540;
//then the remaining hours and minutes
long remainderDays = this.getEstimatedDuration() % 540;
//then we calculate the hours
long workingHours = remainderDays/60;
//and the remaining are the minutes
long workingMinutes = remainderDays % 60;
//convert to calendar to add the estimated time to the given time
Calendar cal = Calendar.getInstance();
cal.setTime(time);
cal.add(Calendar.DATE,(int) workingDays);
cal.add(Calendar.HOUR , (int) workingHours);
cal.add(Calendar.MINUTE, (int) workingMinutes);
//format back to date
String endTime = format.format(cal.getTime());
Date plannedEndTime = format.parse(endTime);
return new TimeSpan(time,plannedEndTime);
}
关于java - 将时间添加到每天 9 小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29876513/