1

您好,我正在尝试使用以下代码,它是“提升代码”的混搭,但它一直在抽出今天的日期和时间。

我试图在 19:00 获得每个月第一个星期二的日期。

我正在使用 W3C School Try-it 进行测试。

<!DOCTYPE html>
<html>
<head>
<script>
function displayDate()
{

var myDate = new Date();
myDate.setHours(19, 00, 0, 0);
myDate.setYear(2013);

myDate.setDate(1);
myDate.setMonth();


//Find Tuesday
var tue = 2;

while(myDate.getDay() != tue) {
    myDate.setDate(myDate.getDate() + 1);

}

document.write(myDate);
</script>
</head>
<body>

<h1>My First JavaScript</h1>
<p id="demo">This is a paragraph.</p>

<button type="button" onclick="displayDate()">Display Date</button>

</body>
</html> 

罗伊

<==更新==>

我使用了您的代码,该代码运行良好,但在下个月的第一个星期二发生后需要考虑在内,我尝试了这个 if 语句但中断了。

function getTuesday() {
    var datenow = new Date();
    var d = new Date(),
        month = d.getMonth(),
        tuedays= [];

    d.setDate(1);

    // Get the first Monday in the month
    while (d.getDay() !== 2) {
        d.setDate(d.getDate() + 1);
    }

    // Get all the other Tuesdays in the month
    while (d.getMonth() === month) {
        tuedays.push(new Date(d.setHours(17,00,00,00)));
        d.setDate(d.getDate() + 7);
    }
If (d.getDate() >= datenow.getDate)
{
    d.setMonth(d.getMonth() + 1);
    document.write(tuedays[1]);
}
Else
{
   document.write(tuedays[1]);
}


}
4

3 回答 3

2

使用以下功能,这将为您提供当前月份的星期二。

function getTuesday() {
    var d = new Date(),
        month = d.getMonth(),
        tuesdays= [];

    d.setDate(1);

    // Get the first Monday in the month
    while (d.getDay() !== 2) {
        d.setDate(d.getDate() + 1);
    }

    // Get all the other Tuesdays in the month
    while (d.getMonth() === month) {
        tuesdays.push(new Date(d.getTime()));
        d.setDate(d.getDate() + 7);
    }

    return tuesdays;
}
于 2013-01-25T09:46:45.210 回答
1

我知道这是旧的,但这是我根据 Sahal 编写的函数编写的函数,它接受一些附加功能。我将通过参数并在下面返回。

function getDates(dayString, month, year, first, allInYear) {
    if (!dayString) { console.error('Missing required parameter: dayString is required.'); return; }
    if (first === undefined || first === null) { first = false; }
    if (allInYear === undefined || allInYear === null) { allInYear = false; }
    if (year === undefined || year === null) { year = new Date().getFullYear(); }
    var converted = false;
    if (month === undefined || month === null) {
        var temp = new Date();
        if (temp.getDate() > 9) {
            month = ((temp.getMonth() + 1) == 12) ? 11 : (temp.getMonth() + 1);
        } else {
            month = temp.getMonth();
        }
        converted = true;
    }
    if (typeof month === "string" && isNaN(parseInt(month))) {
        month = month.toLowerCase().substring(0, 3);
        switch (month) {
            case "jan":
                month = 0;
                break;
            case "feb":
                month = 1;
                break;
            case "mar":
                month = 2;
                break;
            case "apr":
                month = 3;
                break;
            case "may":
                month = 4;
                break;
            case "jun":
                month = 5;
                break;
            case "jul":
                month = 6;
                break;
            case "aug":
                month = 7;
                break;
            case "sep":
                month = 8;
                break;
            case "oct":
                month = 9;
                break;
            case "nov":
                month = 10;
                break;
            case "dec":
                month = 11;
                break;
            default:
                var temp = new Date();
                if (temp.getDate() > 9) {
                    month = ((temp.getMonth() + 1) == 12) ? 11 : (temp.getMonth() + 1);
                } else {
                    month = temp.getMonth();
                }
                converted = true;
                break;
        }
    } else if (typeof month === "number" || (typeof month === "string" && !isNaN(parseInt(month)))) {
        month = (!converted) ? parseInt(month) - 1 : month;
    }
    if (typeof year === "string" && !isNaN(parseInt(year)) || typeof year === "number") {
        if (parseInt(year) / 1000 > 2) {
            year = parseInt(year);
        } else if (parseInt(year) / 10 >= 0 && parseInt(year) / 10 < 10) {
            var temp2 = new Date().getFullYear();
            year = (parseInt(Math.floor(temp2 / 100)) * 100) + parseInt(year);
        }
    } else if (typeof year === "string" && isNaN(parseInt(year))) {
        if (year === "this") {
            year = new Date().getFullYear();
        } else if (year === "last") {
            year = new Date().getFullYear() - 1;
        } else if (year === "next") {
            year = new Date().getFullYear() + 1;
        } else {
            console.warn('Year string not recognized, falling back to current year. (this, last, next).');
            year = new Date().getFullYear();
        }
    }
    var dates = [];
    //hang in there this is going to get a doosie
    var d = new Date(),
        dow = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"],
        getDow = function(sd, dowa) {
            for (var i = 0; i < dowa.length; i++) {
                var day = dowa[i];
                if (sd.toLowerCase().substring(0, 3) == day) {
                    return i;
                }
            }
            return -1;
        },
        di = getDow(dayString, dow),
        getDIM = function(year, mon) {
            var isLeap = ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0));
            return [31, (isLeap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mon];
        };
    d.setFullYear(year);
    d.setMonth(month, 1);
    if (di == -1) { console.error('Range Error: Day of the week should be between sunday and saturday'); return; }
    if (first && !allInYear) {
        while (d.getDay() !== di) {
            d.setDate(d.getDate() + 1);
        }
        return d;
    } else if (first && allInYear) {
        var tm = 0;
        d.setMonth(tm, 1);
        for (var i = tm; i <= 11; i++) {
            while (d.getDay() !== di) {
                d.setDate(d.getDate() + 1);
            }
            dates.push(new Date(d));
            tm += 1;
            d.setMonth(tm, 1);
        }
        return dates;
    } else if (!first && !allInYear) {
        var eom = getDIM(d.getFullYear(), d.getMonth());
        for (var x = 1; x <= eom; x++) {
            if (d.getDay() === di) {
                dates.push(new Date(d));
            }
            d.setDate(d.getDate() + 1);
        }
        return dates;
    } else if (!first && allInYear) {
        var tm = 0;
        for (var i = 0; i <= 11; i++) {
            var eom = getDIM(d.getFullYear(), i),
                dim = [];
            d.setMonth(i, 1);
            for (var x = 1; x <= eom && d.getMonth() == i; x++) {
                if (d.getDay() === di) {
                    dim.push(new Date(d));
                }
                d.setDate(d.getDate() + 1);
            }
            dates.push(dim);
        }
        return dates;
    } else {
        return [];
    }
}

所以唯一需要的参数是日期字符串,您可以选择设置月份,年份,第一个或一个月中的全部以及一年中的全部,月份和年份默认为当前,第一个和allInYear默认为false,但是您可以通过将 null 或 undefined 传递给月份和年份参数,在 moth 中设置第一个。

月份参数接受:null|undefined, number, or string eg 'July'

年份参数接受:null|undefined, number 2 or 4 digit, string eg '19' or '2019' also 'last', 'this', 'next'

返回 Date 对象、Array[Date object...] 或 Array[Array[Date object...]...]

这已经过测试,应该涵盖大多数情况......

于 2019-12-11T17:37:36.193 回答
0

嗯,自从我问这个问题已经 8 年多了,它出现在谷歌“每个月的第一个星期二”的最高结果中。原来的项目现在已经死了,但我获得了更多的经验,我觉得更有资格提供答案。

首先要注意的是,最初的问题并不明显,而且标题同样模棱两可。最初的目标是获得下一个本月的第一个星期二,因此可能是本月或下个月,具体取决于您所在月的位置。

由于问题含糊不清,我试图在答案中解释这些差异。

我的第一个功能是获取给定月份和年份的一周中特定日期的发生情况。感谢@Amadan 在对其中一个答案的评论中。

function GetFirstDayOfMonth(dayOfTheWeek, month, year){
    const date = new Date(year, month, 1);
    date.setDate(date.getDate() + ((7 + dayOfTheWeek) - date.getDay()) % 7)
    return date;
}

下一个函数,获取给定日期的一周中第一个指定日期的下一次出现。

function GetFirstNextFirstDayOfTheWeek(currentDate, day){
    const returnValue = GetFirstDayOfMonth(day, currentDate.getMonth(), currentDate.getFullYear());

    if(returnValue.getDate() < currentDate.getDate()){
        return GetFirstNextFirstDayOfTheWeek(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1), day);
    }

    return returnValue;
}

因此,要实现原始问题,我可以运行以下示例

const tuesday = 2;

function GetFirstNextFirstTuesday(){
    return GetFirstNextFirstDayOfTheWeek(new Date(), tuesday);
}

实现每月的第一个星期二

const tuesday = 2;

function GetFirstTuesday(month, year){
    return GetFirstDayOfMonth(tuesday, month, year);
}

并完成给定年份的所有第一个星期二。

const tuesday = 2;

function GetFirstTuesdayOfEveryMonth(year){
    const dates = [];
    for (let index = 0; index < 12; index++) {
        dates.push(GetFirstDayOfMonth(tuesday, index, year));    
    }
    return dates;
}

function GetFirstDayOfMonth(dayOfTheWeek, month, year){
    // Get the first day of the month
    const date = new Date(year, month, 1);
    // Set the date based on the day of the week. 
    date.setDate(date.getDate() + ((7 + dayOfTheWeek) - date.getDay()) % 7)
    return date;
}

function GetFirstNextFirstDayOfTheWeek(currentDate, day){
    const returnValue = GetFirstDayOfMonth(day, currentDate.getMonth(), currentDate.getFullYear());

    if(returnValue.getDate() < currentDate.getDate()){
        return GetFirstNextFirstDayOfTheWeek(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1), day);
    }

    return returnValue;
}

const tuesday = 2;

function GetFirstTuesday(month, year){
    return GetFirstDayOfMonth(tuesday, month, year);
}

function GetFirstNextFirstTuesday(){
    return GetFirstNextFirstDayOfTheWeek(new Date(), tuesday);
}


function GetFirstTuesdayOfEveryMonth(year){
    const dates = [];
    for (let index = 0; index < 12; index++) {
        dates.push(GetFirstDayOfMonth(tuesday, index, year));    
    }
    return dates;
}



console.log(GetFirstNextFirstTuesday());
console.log(GetFirstTuesday(09, 2021));
console.log(GetFirstTuesdayOfEveryMonth(2022));

希望这可以帮助任何似乎在这篇旧帖子上发茬的人,并感谢那些回答的人。

于 2021-10-14T15:35:28.970 回答