1

我有两个日期,招聘 11/19/2013 和 endhiring 10/01/2014,两者都转换为总小时数,不考虑周末,但它们有不同的年份,因此输出显示:总工作时间是 - 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 ;
}
4

3 回答 3

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

您可以通过将日历转换为日期来获得它们之间的毫秒数(日历有这样的方法来做到这一点)

于 2013-11-09T03:36:15.153 回答
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);  
}

顺便说一句,您的原始代码有一个微妙的“差一个”错误。totalamountDays 的减法不包括结束日,但在扣除周末时,循环包括结束日。

于 2013-11-09T04:23:43.907 回答
0

为什么这么复杂?

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

通过除以86400000 first,然后减去,每个日期有什么时间都没有关系。

FYI86400000是一天中的毫秒数。

于 2013-11-09T03:38:13.340 回答