是否可以将工作日添加到 joda 时间?
例如,如果当前日期是 01/03 星期五,则 date + 1 应该返回星期一 04/03,而不是 02/03。
据我所知,在 Joda Time 中没有内置方法可以自动为您执行此操作。但是,您可以编写自己的方法,在循环中递增日期,直到到达工作日。
请注意,根据您的确切需要,这可能比您想象的要复杂得多。例如,它也应该跳过假期吗?哪天是假期取决于您所在的国家/地区。此外,在某些国家/地区(例如阿拉伯国家),周末是周四和周五,而不是周六和周日。
LocalDate newDate = new LocalDate();
int i=0;
while(i<days)//days == as many days as u want too
{
newDate = newDate.plusDays(1);//here even sat and sun are added
//but at the end it goes to the correct week day.
//because i is only increased if it is week day
if(newDate.getDayOfWeek()<=5)
{
i++;
}
}
System.out.println("new date"+newDate);
请注意,一次添加 N 天迭代可能相对昂贵。对于较小的 N 值和/或对性能不敏感的代码,这可能不是问题。在哪里,我建议通过计算您需要调整多少周和几天来最小化添加操作:
/**
* Returns the date that is {@code n} weekdays after the specified date.
* <p>
* Weekdays are Monday through Friday.
* <p>
* 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);
public LocalDate getBusinessDaysAddedDate(LocalDate localDate, int businessDays){
LocalDate result;
if(localDate.getDayOfWeek().getValue() + businessDays > 5) {
result = localDate.plusDays(2);
}
result = localDate.plusDays(businessDays);
return result;
}
为了使用 Date 而不是 LocalDate,请参阅https://stackoverflow.com/a/47719540/12794444进行转换。
类YearMonthDay已弃用,您不应使用它。如果您更改为简单的 DateTime,您可以通过调用以下方式获取工作日:
dateTime.getDayOfWeek();
星期五将是 5。
其中一种方法可以是制作一个看起来像这样的自定义 addDays 方法:
addDays(DateTime dateTime, int days) {
for(int i=0;i<days;i++){
dateTime.plusDays(1);
if(dateTime.getDayOfWeek()==6) dateTime.plusDays(2); // if Saturday add 2 more days }
}