Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 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.*

like image 475
p.campbell Avatar asked Oct 20 '09 15:10

p.campbell


1 Answers

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
}
like image 108
csj Avatar answered Sep 23 '22 00:09

csj