开发者

JavaScript - find date of next time change (Standard or Daylight)

开发者 https://www.devze.com 2022-12-08 19:44 出处:网络
Here\'s a timely question. The rules in North America* for time change are: the first Sunday in November, offset changes to Standard (-1 hour)

Here's a timely question. The rules in North America* for time change are:

  • the first Sunday in November, offset changes to Standard (-1 hour)
  • the second Sunday in March, offset changes to Daylight (your normal offset from GMT)

Consider 开发者_JAVA百科a function in JavaScript that takes in a Date parameter, and should determine whether the argument is Standard or Daylight Saving.

The root of the question is:

  • how would you construct the date of the next time change?

The algorithm/pseudocode currently looks like this:

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
    }

}

The constraint here is to use the standard JavaScript function, and not scrape any JavaScript engine's parsing of the Date object. This code won't be running in a browser, so those nice solutions wouldn't apply.

**not all places/regions in North America change times.*


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) I expect there could be some other rules in different countries. Some don't have daylight saving at all. So to find the answer in a specific locale you could probably loop throught 365(6) days to find the days where getTimetoneOffset() changes it's value. This should not be a big lag in performance.

2) Then, you can get the specific hour when the time is changes (2 am for US?). Suggest another loop throught 24 hours


PS: Ok, someone has already done the job =). You should test it before using (because I didn't test)

PPS: Your first question was "is daylight applied or not for specific date?". This answer solves the task

0

精彩评论

暂无评论...
验证码 换一张
取 消