寻找第二个和第四个星期二每月的使用Javascript(Finding the second and

2019-09-02 09:36发布

我协会已在每个月的第二个和第四个星期二会议,我真的很喜欢一个Javascript代码,所以我没有更新我们的网站每两个星期,下次会议的日期可以计算并自动显示。

我真的很感激一些帮助,因为我有在Javascript中绝对没有skils,只有在CSS和HTML。

Answer 1:

这是一个解决方案

HTML

<ul id="list"></ul>

使用Javascript

function getTuesdays(month, year) {
    var d = new Date(year, month, 1),
        tuesdays = [];

    d.setDate(d.getDate() + (9 - d.getDay()) % 7)
    while (d.getMonth() === month) {
        tuesdays.push(new Date(d.getTime()));
        d.setDate(d.getDate() + 7);
    }

    return tuesdays;
}

var meetingTuesdays = [],
    ul = document.getElementById("list"),
    temp,
    li,
    i;

for ( i = 0; i < 12; i += 1) {
    temp = getTuesdays(i, 2013);
    meetingTuesdays.push(temp[1]);
    li = document.createElement("li");
    li.textContent = temp[1];
    ul.appendChild(li);

    meetingTuesdays.push(temp[3]);
    li = document.createElement("li");
    li.textContent = temp[3];
    ul.appendChild(li);
}

console.log(meetingTuesdays);

上的jsfiddle

更新:为您进一步的论证

使用Javascript

function getTuesdays(month, year) {
    var d = new Date(year, month, 1),
        tuesdays = [];

    d.setDate(d.getDate() + (9 - d.getDay()) % 7)
    while (d.getMonth() === month) {
        tuesdays.push(new Date(d.getTime()));
        d.setDate(d.getDate() + 7);
    }

    return tuesdays;
}

var today = new Date(),
    theseTuesdays = getTuesdays(today.getMonth(), today.getFullYear()),
    next;

theseTuesdays.some(function (tuesday, index) {
    if (index % 2 === 1 && tuesday > today) {
        next = tuesday;
        return true;
    }

    return false;
});

alert("Our next meeting is on : " + moment(next).format("MMMM Do YYYY"));

上的jsfiddle



文章来源: Finding the second and fourth Tuesday of the month with Javascript