JavaScript - 查找下次更改的日期(标准或日光)

时间:2009-10-20 15:32:14

标签: javascript algorithm datetime

这是一个及时的问题。北美*关于时间变化的规则是:

  • 11月的第一个星期天,将标准偏差(-1小时)
  • 三月的第二个星期天,抵消日光的变化(您与GMT的正常偏差)

考虑JavaScript中的一个函数,该函数接受Date参数,并应确定参数是标准还是夏令时。

问题的根源是:

  • 你将如何构建下次更改的日期?

算法/伪代码目前看起来像这样:

if argDate == "March" 
{

    var firstOfMonth = new Date();
    firstOfMonth.setFullYear(year,3,1);

    //the day of week (0=Sunday, 6 = Saturday)
    var firstOfMonthDayOfWeek = firstOfMonth.getDay();

    var firstSunday;

    if (firstOfMonthDayOfWeek != 0) //Sunday!
    {
        //need to find a way to determine which date is the second Sunday
    }

}

这里的约束是使用标准的JavaScript函数,而不是刮掉任何JavaScript引擎对Date对象的解析。此代码不会在浏览器中运行,因此这些不错的解决方案将不适用。

**并非所有北美地区/地区都会改变时间。*

2 个答案:

答案 0 :(得分:1)

if argDate == "March" 
{

    var firstOfMonth = new Date();
    firstOfMonth.setFullYear(year,3,1);

    //the day of week (0=Sunday, 6 = Saturday)
    var firstOfMonthDayOfWeek = firstOfMonth.getDay();

    var daysUntilFirstSunday =  (7-firstOfMonthDayOfWeek) % 7;

    var firstSunday = firstOfMonth.getDate() + daysUntilFirstSunday;

    // first Sunday now holds the desired day of the month
}

答案 1 :(得分:0)

1)我预计不同国家可能会有其他规则。有些人根本没有夏令时。因此,要在特定区域设置中找到答案,您可以在365(6)天内循环查找getTimetoneOffset()更改其值的日期。这不应该是性能上的大滞后。

2)然后,您可以在时间变化时获取特定小时(美国凌晨2点?)。建议在24小时内完成另一个循环


PS:好的,someone has already done the job =)。您应该在使用之前测试它(因为我没有测试)

PPS:您的第一个问题是“是否适用于特定日期的日光?”This answer solves the task