Calculating end date while skipping holidays + Joda time

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-18 06:17:06

问题


I would like to calculate end date (and time) of an event. I know starting date and duration (in minutes). But:

  1. I have to skip holidays - non-recurrent situation
  2. I have to skip weekends - recurrent situation
  3. I have to not count working time (e.g: from 8:00am till 5:00pm) - recurrent situation, but with finer granularity

Is there a simple way to achieve these cases using Joda time library?


回答1:


Jodatime will help you -a lot I'd say-, but you'll need to write the logic yourself, a loop skipping some entire days and some times of the day. Not very simple, neither very complex, it seems to me.




回答2:


Have you looked into Holiday calculation project? it is featured in the Related projects from jodatime and could be useful




回答3:


First you have to define "holidays". Not every locale has the same ones, so this has to be made generic and pluggable.

I don't think it's "simple".




回答4:


Here's some code I use. dtDateTimes can contain your pre-defined holiday dates (e.g. UK Bank Holidays) and dtConstants can contain recurring things you'd like to match against, like DateTimeConstants.SATURDAY.

/**
 * Returns a tick for each of
 * the dates as represented by the <code>dtConstants</code> or the list of <code>dtDateTimes</code>
 * occurring in the period as represented by begin -> end.
 * 
 * @param begin
 * @param end
 * @param dtConstants
 * @param dtDateTimes
 * @return
 */
public int numberOfOccurrencesInPeriod(final DateTime begin, final DateTime end, List<Integer> dtConstants, List<DateTime> dtDateTimes) {
    int counter = 0;
    for (DateTime current = begin; current.isBefore(end); current = current.plusDays(1)) {
        for (Integer constant : dtConstants) {
            if (current.dayOfWeek().get() == constant.intValue()) {
                counter++;
            }
        }
        for (DateTime dt : dtDateTimes) {
            if (current.getDayOfWeek() == (dt.getDayOfWeek())) {
                counter++;
            }
        }

    }
    return counter;
}

/**
 * Returns true if the period as represented by begin -> end contains any one of
 * the dates as represented by the <code>dtConstants</code> or the list of <code>dtDateTimes</code>
 *  
 * @param begin
 * @param end
 * @param dtConstants
 * @param dtDateTimes
 */
public boolean isInPeriod(final DateTime begin, final DateTime end, List<Integer> dtConstants, List<DateTime> dtDateTimes) {
    return numberOfOccurrencesInPeriod(begin, end, dtConstants, dtDateTimes) > 0;
}


来源:https://stackoverflow.com/questions/2751302/calculating-end-date-while-skipping-holidays-joda-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!