确定DST何时生效

时间:2013-04-07 15:52:05

标签: javascript time timezone dst

我最近遇到了一个问题...

假设我有一些像这样的Javascript,例如:

var timezone = -(new Date()).getTimezoneOffset() / 60; // Get the TZ offset

var local = [];
var gmt   = [];

for(var i = 0; i <= 23; i++) // Loop through each hour
{
    local.push(i);

    var time = (i + timezone);

    if(time == 24)
        time = 0;

    gmt.push(time);
}

这不是在DST中完美运行,但是当DST出现时,我有意想不到的结果,例如:(本地用户在GMT / DST中)

> console.log(local);
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

> console.log(gmt);
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 0]

两个数组应该相同。

如何检测夏令时何时生效?

2 个答案:

答案 0 :(得分:0)

此功能将帮助您使用DST进行计算。

function dstOffset() {
    var dailyOffsets = [];
    for (var i = 0; i <= 366; i++) { // sample timezone offset over at least a year since daylight saving changes are repeated each year.
        var sampleDay = new Date(); // today at whatever time
        sampleDay.setDate(i); // i days from the begining of this month (at the same time)
        dailyOffsets.push(sampleDay.getTimezoneOffset());
    }
    return Math.min.apply(null, dailyOffsets);
}
alert(dstOffset() + " minutes");

答案 1 :(得分:0)

这是我最终得到的,检测到3月的最后一个星期日,然后是10月的最后一个星期日,检查我们目前是否在这些日子里。感谢您的评论和答案,每个人。

随意编辑并为我提供建议/改进。我觉得这不是最好的方法。

function is_bst()
{
    var date    = new Date();
    var march   = null;
    var october = null;

    for(var i = 7; i != 0; i--)
    {
        var day = new Date(date.getFullYear(), 2, i);

        if(day.getDay() == 0)
        {
            march = day;
            break;
        }
    }

    for(var i = 7; i != 0; i--)
    {
        var day = new Date(date.getFullYear(), 9, i);

        if(day.getDay() == 0)
        {
            october = day;
            break;
        }
    }

    return !(date < march || date > october);
}