如何计算两个日期之间的总工时?

时间:2013-11-09 03:25:28

标签: java algorithm validation date

我有两个约会,招聘11/19/2013和2014年10月1日结束,两个都转换为总小时数,不考虑周末,但他们有不同的年份,因此输出说:总小时工作是-1200:

private int calculateTimeInternship(Vacancy peoplevacancy){
    int hourWorked = 0; 
    Calendar date1 = Calendar.getInstance();  
    Calendar date2 = Calendar.getInstance();    

    date1.setTime(peoplevacancy.getDthiring());  
    date2.setTime(peoplevacancy.getDtendhiring());  

    int initiation = date1.get(Calendar.DAY_OF_YEAR);  
    int end = date2.get(Calendar.DAY_OF_YEAR);  

    int amountDay = (initiation - end) + 1;  

    for (; initiation <= end; inicio++){  
        if (date1.get(Calendar.DAY_OF_WEEK) == 1   || date1.get(Calendar.DAY_OF_WEEK) == 7)  
        amountDay--;  

        date1.add(Calendar.DATE, 1);  
    }

    hourWorked = amountDay * 4 //4 hour per day;
    return hourWorked ;
}

3 个答案:

答案 0 :(得分:1)

Joda可以帮助您,但由于其许可证,我永远无法使用它。

如果像我一样,Joda不适合你,你可以解决这个问题如下:

initialize endDate object
initialize startDate object
initialize weeksBetween as 
    milliseconds between end&start/milliseconds per day, divided by seven (integer floor). 
    //may need to normalize dates and set them to be both midnight or noon or some common time
initialize daysBetween = weeksBetween*5 // in any continuous 7 days, 5 are weekdays.
initialize curDay=startDate + weeksBetween*7 days

while(curDay is not endDate)
   add a day to curDay
   if(curDay is not weekend)
      daysBetween++
output daysBetween* 4

您可以通过将日历转换为Date来获取它们之间的毫秒数(日历有这样的方法来执行此操作)

答案 1 :(得分:0)

为什么这么复杂?

private int calculateTimeInternship(Vacancy vacancy) {
    return 4 * ((int)(vacancy.getDtendhiring().getTime() / 86400000L - vacancy.getDthiring().getTime() / 86400000L) + 1);  
}

首先除以86400000 ,然后减去,每个日期的每个时间都没关系。

FYI 86400000是一天中的毫秒数。

答案 2 :(得分:0)

你已经完成了实习的每一天,所以为什么不算简单算一下工作日呢?

int amountDay = 0;
while (date1.compareTo(date2) <= 0) {
    if (date1.get(Calendar.DAY_OF_WEEK) != 1
    &&  date1.get(Calendar.DAY_OF_WEEK) != 7)  
        amountDay++;  
    date1.add(Calendar.DATE, 1);  
}

顺便说一句,你的原始代码有一个微妙的“一个一个”的错误。总金额的减法日排除结束日,但循环包括扣除周末的结束日。