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

p.c*_*ell 6 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对象的解析.此代码不会在浏览器中运行,因此这些不错的解决方案将不适用.

**并非所有北美地区/地区都会发生变化.*

csj*_*csj 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
}
Run Code Online (Sandbox Code Playgroud)