6

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

p.campbell
  • 98,673
  • 67
  • 256
  • 322

2 Answers2

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
}
csj
  • 21,818
  • 2
  • 20
  • 26
0

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

Community
  • 1
  • 1
Dan
  • 55,715
  • 40
  • 116
  • 154