在跳过假期+ Joda时间时计算结束日期
我想计算一个事件的结束日期 (和时间)。 我知道开始日期和持续时间 (以分钟为单位)。 但:
- 我不得不跳过假期 – 非经常性情况
- 我不得不跳过周末 – 经常出现的情况
- 我不计算工作时间(例如:从早上8点到下午5点) – 经常出现的情况,但细粒度更细
有没有一种简单的方法来使用Joda时间库来实现这些情况?
Jodatime会帮助你 – 我会说很多 – 但是你需要自己编写逻辑,一个循环跳过一整天和一天的某些时间。 在我看来,不是很简单,也不是很复杂。
首先,你必须定义“假期”。 并非每个语言环境都具有相同的语言环境,因此必须将其设置为通用且可插入的。
我不认为它“简单”。
你看过假期计算项目了吗? 它在jodatime的相关项目中有特色,可能很有用
这是我使用的一些代码。 dtDateTimes
可以包含您预定义的假日日期(例如英国银行假期),而dtConstants
可以包含您想要匹配的重复DateTimeConstants.SATURDAY
,例如DateTimeConstants.SATURDAY
。
/** * Returns a tick for each of * the dates as represented by the
dtConstants
or the list ofdtDateTimes
* 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, ListdtConstants, List 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 dtConstants
or the list ofdtDateTimes
* * @param begin * @param end * @param dtConstants * @param dtDateTimes */ public boolean isInPeriod(final DateTime begin, final DateTime end, ListdtConstants, List dtDateTimes) { return numberOfOccurrencesInPeriod(begin, end, dtConstants, dtDateTimes) > 0; }