2009-10-20 62 views
6

以下是一个及时的问题。对于时间的变化在北美*的规则是:JavaScript - 查找下一次更改日期(标准或日光)

  • 第一个星期日十一月,抵消月更改为标准(-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函数,而不是刮Date对象的任何JavaScript引擎的解析。此代码不会在浏览器中运行,因此这些不错的解决方案不适用。

**不是所有的地方/在北美的更换时间的区域。*

回答

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 
} 
0

1)我希望有可能是在不同国家的一些其他规则。有些根本没有夏令时。因此,要在特定区域设置中找到答案,您可能需要循环365(6)天以查找getTimetoneOffset()更改其值的日期。这不应该是一个很大的表现滞后。 2)然后,当时间变化时(美国凌晨2点),你可以得到特定的小时。建议在24小时内通过另一个环路


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

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