开发者

Seconds between two dates, limited to variable working hours

I need to get the amount of seconds between two dates, and o开发者_运维技巧nly during working hours (ex 0800-1600). Any suggestions on how to do this in Java?

long seconds = ((datenow.getTime() - datethen.getTime()) / 1000);


You could use something like this:

public static void main(String[] args) {
    Calendar cal1 = Calendar.getInstance();
    cal1.set(2011, 10, 10, 12, 00, 00);
    Date datenow = cal1.getTime();

    Calendar cal2 = Calendar.getInstance();
    cal2.set(2011, 10, 14, 15, 00, 00);
    Date datethen = cal2.getTime();

    // check for weekends
    long daynow = TimeUnit.MILLISECONDS.toDays(datenow.getTime());
    long daythen = TimeUnit.MILLISECONDS.toDays(datethen.getTime());
    long daydiff = daythen - daynow;
    long weekenddiff = daydiff / 7; // number of weekends

    if (cal1.get(Calendar.DAY_OF_WEEK) > cal2.get(Calendar.DAY_OF_WEEK)) {
        weekenddiff++;// we have a weekend but not another full week;
    }
    long secDiff = TimeUnit.SECONDS.convert(16, TimeUnit.HOURS);
    long weekendAdditionalSecDiff = TimeUnit.SECONDS.convert(16, TimeUnit.HOURS); // 16 additional hours for the weekend

    // 16 non-work hours between two shifts
    daydiff *= secDiff;
    daydiff += (weekenddiff * weekendAdditionalSecDiff); 
    long workDiffSeconds = TimeUnit.SECONDS.convert(
            datethen.getTime() - datenow.getTime(),
            TimeUnit.MILLISECONDS) - daydiff; 
    System.out.println("Difference in working hours is "
            + workDiffSeconds + " seconds");
    System.out.println("Difference in working hours is "
            + TimeUnit.HOURS.convert(workDiffSeconds, TimeUnit.SECONDS) + " hours");
}

which first calculates the number of days between your days and subtracts the number of non-work-time-seconds from the real difference.

For the weekends, 8 additional non-work-hours per day are added.


When I did this, I found it easiest to take two dates, start and end.

Then express each in seconds.

Then find midnight of each date by taking the mod of each and 86400 (seconds per day).

And then it's easy figure from there. The key was to locate the end points of the interval at midnight.


  1. Use something like Joda Time, (but it can be solved without).
  2. Assuming day_now < date_then.
    1. Figure the answer for day_now (datenow to midnight of datenow)
    2. Figure the answer for day_then (midnight of day before then to datethen)
    3. Figure out the number of days in between.
    4. Combine 1, 2, and 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜