如何刷新某个月的页面。 JS

时间:2014-01-30 19:00:19

标签: javascript date datetime

我有一个功能可以在特定的时间和日期刷新我的页面但是如何才能在特定时间刷新特定的月份和日期?我之所以这样做,是因为我的网站会检查仅在特定月份进行的足球转会更新。

以下是我一天刷新特定时间的功能

function refreshAt(hours, minutes, seconds, day) {
    var now = new Date();
    var then = new Date();
    var dayUTC = new Date();

    if(dayUTC.getUTCDay() == day) {

        if(now.getUTCHours() > hours ||
        (now.getUTCHours() == hours && now.getUTCMinutes() > minutes) ||
        now.getUTCHours() == hours && now.getUTCMinutes() == minutes && now.getUTCSeconds() >= seconds) {
            then.setUTCDate(now.getUTCDate() + 1);
        }

        then.setUTCHours(hours);
        then.setUTCMinutes(minutes);
        then.setUTCSeconds(seconds);


        var timeout = (then.getTime() - now.getTime());
        setTimeout(function() { window.location.reload(true); }, timeout);
    }
}

1 个答案:

答案 0 :(得分:2)

我已经清理了一下你的代码,并添加了一行,也可以让你设置一个特定的日期和月份:

function refreshAt(hours, minutes, seconds, day, month) { // added month argument
    var now = new Date();
    var then = new Date( // used format: new Date(Y, M, D, h, m, s);
        now.getUTCFullYear(),
        month!=undefined ? month : now.getUTCMonth(),
        day,
        hours,
        minutes,
        seconds
    ); // fill in the date when defining the variable

    // You don't need a seperate Date object to get the UTC date

    if (now.getUTCDate() == day && (month == undefined || now.getUTCMonth() == month)) {
        if(now.getTime() > then.getTime()) {
            then.setUTCDate(now.getUTCDate() + 1);
        }

        // exit function if the new time is still after the current time
        if (now.getTime() > then.getTime()) return;

        // you don't need brackets around this
        var timeout = then.getTime() - now.getTime();
        setTimeout(function() { window.location.reload(true); }, timeout);
    }
}

我希望评论能说清楚我做了哪些修改。如果仍然不清楚,请对此答案发表评论。

month!=undefined ? month : now.getUTCMonth(),行执行以下操作:

如果月份未定义,则填写月份,如果未填写,则使用当前月份。这意味着使用以下语法仍然有效:

refreshAt(23, 59, 59, 30); //refreshes at 23:59:59 UTC today (30 Jan 2014)

Date作为参数

您还可以通过提供Date对象作为参数而不是每个单独的变量来使这更容易。这看起来像这样:

function refreshAt(date) { // added month argument
    var now = new Date();

    if (now.getUTCDate() == date.getUTCDate()) {
        var timeout = date.getTime() - now.getTime();
        if (timeout > 0)
            setTimeout(function() { window.location.reload(true); }, timeout);
    }
}

然后可以通过

调用它
refreshAt(new Date(2014, 0, 30, 23, 59, 59));

这将为2014年1月30日23:59:59 UTC设置刷新计时器。