获得每个月的第一个和第五个工作日

时间:2014-09-23 15:38:23

标签: javascript

代码或函数的任何示例,它将告知指示日期是当月的第1个工作日还是第5个工作日。

营业日为周一至周五

实施例。通过传递格式yyyy-MM-dd的当前日期,如果当前日期对应于第1个或第5个工作日,则函数或代码可以返回true。

2 个答案:

答案 0 :(得分:1)

可能不是最好的解决方案,但它会起作用:

function checkIfFirstFithBusinessDay(day, month, year) {

    // check that it is a valid date
    if (!isNaN(day) && !isNaN(month) && !isNaN(year) && month > 0 && month < 13 && day > 0 && day < 32) {

        var d = new Date(year, month-1, day);

        // If the day does not much, that means that the original date was incorrect (e.g.: Feb 30)
        if (d.getDate() != day) { return false; }

        // month - 1, because months in JavaScript go from 0 (January) to 11 (December)
        var auxDate = new Date(year, month-1, 1);
        var first, fifth;

        switch (d.getDay()) {
            case 0: // the 1st of the month is Sunday --> first business day is the 2nd (Monday)
                first = 2; fifth = 6;
                break;
            case 6: // the 1st of the month is Saturday --> first business day is the 3rd (Monday)
                first = 3; fifth = 7;
                break;
            default:
                first = 1; fifth = 5;
                if      ((d.getDay() + fifth + 6) % 7 == 0) { fifth = 6; } // sunday
                else if ((d.getDay() + fifth + 6) % 7 == 6) { fifth = 7; } // saturday
                break;
        }

        var firstBusinessDay = new Date(year, month-1, first);
        var fifthBusinessDay = new Date(year, month-1, fifth);

        return (d.getTime() === firstBusinessDay.getTime() || d.getTime() === fifthBusinessDay.getTime());

    } else {

        return false;

    }

}

然后,您只需要调用函数:firstAndFithBusinessDay(28, 12, 2000)

只需几件事:

  • 参数分别为日,月和年(欧式)。
  • 此解决方案未考虑假期。
  • 您可以轻松更改代码,以检测它是第一个还是第五个工作日。

答案 1 :(得分:1)

我的兴趣被你的问题激怒了。

这绝不是完美的,但它在一些快速测试中表现不错。 您应该在2014年9月的第5个工作日将其作为getNthBusinessDay(5, 9, 2014)调用。在这种情况下,它会返回文本Friday等等

var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

function getNthBusinessDay(n, month, year) {
    var worked = 0;
    for (var i = 1; i <= 31; i++) {
        var testDate = new Date(year, month - 1, i);
        var day = testDate.getDay();
        if (day > 0 && day < 6) {
            if (++worked == n) {
                return days[day];
            }
        }
    }
}