How to add Business hours to Date considering not adding weekends ? - Java

前端 未结 7 949
盖世英雄少女心
盖世英雄少女心 2020-12-12 04:47

I want to add certain number of hours to date, ignoring the weekends

For example,

(Friday 18:00) + 48 = (Tuseday 18:00) (Saturday and Sunday are ignored)

7条回答
  •  Happy的楠姐
    2020-12-12 05:21

    I would strongly recommend using JodaTime (or DateTimeof Java8) for this, since the old Date/Calendar API is pretty useless.

    public DateTime getEndtime(final DateTime startdate, final int hours) {
        final DateTime endOfWeek = endOfWeek(startdate);
    
        final Duration restOfWeek = new Duration(startdate, endOfWeek);
    
        final Duration hoursDuration = toDuration(hours);
        if (restOfWeek.isLongerThan(hoursDuration)) {
            return startdate.plus(hoursDuration);
        } else {
            final Duration durationForNextWeek = hoursDuration.minus(restOfWeek);
            return startOfWeek(startdate).plus(durationForNextWeek);
        }
    }
    
    //Converts number of hours as int to Duration
    private Duration toDuration(final int hours) {
        return new Duration(hours * 60 * 60 * 1000);
    }
    
    //Returns coming friday, 1 millisecond to midnight
    private DateTime endOfWeek(final DateTime dateTime) {
        DateTime copy = dateTime;
        while (copy.getDayOfWeek() != 6) {
            copy = copy.plusDays(1);
        }
    
        return copy.toDateMidnight().toDateTime().minusMillis(1);
    }
    
    //Returns the following monday at midnight
    //If dateTime is on a monday, the next monday will be chosen
    private DateTime startOfWeek(final DateTime dateTime) {
        DateTime copy = dateTime.plusDays(1);
        while (copy.getDayOfWeek() != 1) {
            copy = copy.plusDays(1);
        }
    
        return copy.toDateMidnight().toDateTime();
    }
    

    Explanation of the code:

    • Check whether the number of hours can be added without crossing into a weekend
    • If no, just add the hours to the startdate
    • If yes, find the duration to be transferred to the next week, and add it to the start of the week

    This code NOT support tasks stretching over multiple weeks, but it's a start that you can modify to support this.. Might be some edge cases that aren't handled as well, I'll leave it to you to test it thoroughly.

提交回复
热议问题