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

时间:2012-10-04 13:38:13

标签: java jodatime

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

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

5 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:5)

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);

答案 2 :(得分:1)

请注意,一次添加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);

答案 3 :(得分:0)

    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;
    }

要使用日期而不是LocalDate,请参考https://stackoverflow.com/a/47719540/12794444进行转换。

答案 4 :(得分:-4)

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    }
}