将时间添加到9小时

时间:2015-04-26 10:33:13

标签: java date calendar

我正在开发一个管理任务的基础项目。工作日为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);
    }

3 个答案:

答案 0 :(得分:2)

我找到了使用模运算符的解决方案,解释在评论中:

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);
}

答案 1 :(得分:0)

如果估计的持续时间以分钟为单位,为什么您不直接添加会议记录?

calendar.add(Calendar.MINUTE, yourMinutes);

答案 2 :(得分:0)

cal.add(Calendar.MINUTE, (int)taskMinutes);设置为taskMinutes并确保其不大于int后,使用getEstimatedDuration()