如何跳过周末同时加入天LocalDate在Java中8? [英] How to skip weekends while adding days to LocalDate in Java 8?

查看:1079
本文介绍了如何跳过周末同时加入天LocalDate在Java中8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其他答案参考乔达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()));
}

这篇关于如何跳过周末同时加入天LocalDate在Java中8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆