joda时间 – 添加工作日到目前为止

是否可以将工作日添加到joda时间?

例如,如果当前日期是01/03周五,则日期+ 1应该返回04/03周一,而不是02/03。

据我所知,在Joda Time中没有为你自动执行此操作的内置方法。 但是,您可以编写自己的方法,在循环中递增日期,直到达到工作日。

请注意,根据您的需要,这可能会比您想象的要复杂得多。 例如,它是否应该跳过假期? 哪些日子是假期取决于你所在的国家。此外,在一些国家(例如阿拉伯国家),周末是周四和周五,而不是周六和周日。

 LocalDate newDate = new LocalDate(); int i=0; while(i 

请注意,一次添加N天迭代可能相对昂贵。 对于N和/或非性能敏感代码的小值,这可能不是问题。 如果是这样,我建议您通过计算需要调整的周数和天数来最小化添加操作:

 /** * Returns the date that is {@code n} weekdays after the specified date. * 

* Weekdays are Monday through Friday. *

* If {@code date} is a weekend, 1 weekday after is Monday. */ public static LocalDate weekdaysAfter(int n, LocalDate date) { if (n == 0) return date; if (n < 0) return weekdaysBefore(-n, date); LocalDate newDate = date; int dow = date.getDayOfWeek(); if (dow >= DateTimeConstants.SATURDAY) { newDate = date.plusDays(8 - dow); n--; } int nWeeks = n / 5; int nDays = n % 5; newDate = newDate.plusWeeks(nWeeks); return ( (newDate.getDayOfWeek() + nDays) > DateTimeConstants.FRIDAY) ? newDate.plusDays(nDays + 2) : newDate.plusDays(nDays);

不推荐使用ClassMonthDay类,您不应该使用它。 如果您更改为简单的DateTime,您可以通过以下方式获取工作日:

 dateTime.getDayOfWeek(); 

周五将是5。

其中一种方法可以是制作一个自定义的addDays方法,该方法看起来像这样:

 addDays(DateTime dateTime, int days) { for(int i=0;i