如何跳过周末同时加入天LocalDate在Java中8?跳过、周末、Java、LocalDate

2023-09-11 03:52:32 作者:奶茶,我只要敌敌畏

其他答案参考乔达API。 我想用java.time做到这一点。

Other answers here refer to Joda API. I want to do it using java.time.

假设今天的日期是2015年11月26日星期四,当我添加2个工作日内给它, 我要的结果,截至周一2015年11月30日。

Suppose today's date is 26th Nov 2015-Thursday, when I add 2 business days to it, I want the result as Monday 30th Nov 2015.

我的工作我自己的实现,但如果东西已经存在,那就太好了!

I am working on my own implementation but it would be great if something already exists!

编辑:

有没有办法从遍历做到与众不同?

Is there a way to do it apart from looping over?

我是想获得一个功能,如: Y = F(X1,X2),其中 Y是实际天数增加, X1是工作日数的增加, X2是星期几(1日〜7日)。

I was trying to derive a function like: Y = f(X1,X2) where Y is actual number of days to add, X1 is number of business days to add, X2 is day of the week (1-Monday to 7-Sunday).

然后给予X1和X2(从日期的周的日获得),我们可以发现Y和然后使用plusDays()LocalDate的方法。 我一直没能得出它为止,它并不一致。任何人都可以证实,循环一遍,直到加入工作日的所需数量是唯一的出路?

Then given X1 and X2 (derived from day of week of the date), we can find Y and then use plusDays() method of LocalDate. I have not been able to derive it so far, its not consistent. Can anyone confirm that looping over until desired number of workdays are added is the only way?

推荐答案

下面的方法将天一个接一个,跳过周末,对于正值个工作日

The following method adds days one by one, skipping weekends, for positive values of workdays:

public LocalDate add(LocalDate date, int workdays) {
    if (workdays < 1) {
        return date;
    }

    LocalDate result = date;
    int addedDays = 0;
    while (addedDays < workdays) {
        result = result.plusDays(1);
        if (!(result.getDayOfWeek() == DayOfWeek.SATURDAY ||
              result.getDayOfWeek() == DayOfWeek.SUNDAY)) {
            ++addedDays;
        }
    }

    return result;
}

经过一番摆弄周围,我想出了一个算法的计算的工作日数增加:

After some fiddling around, I came up with an algorithm to calculate the number of workdays to add:

public long getActualNumberOfDaysToAdd(long workdays, int dayOfWeek) {
    if (dayOfWeek < 6) { // date is a workday
        return workdays + (workdays + dayOfWeek - 1) / 5 * 2;
    } else { // date is a weekend
        return workdays + (workdays - 1) / 5 * 2 + (7 - dayOfWeek);
    }
}

public LocalDate add2(LocalDate date, long workdays) {
    if (workdays < 1) {
        return date;
    }

    return date.plusDays(getActualNumberOfDaysToAdd(workdays, date.getDayOfWeek().getValue()));
}