JavaScript - find the date of the next time change (standard or daylight)

That is the question. Rules in North America * for changing the time:

  • the first Sunday of November , the shift of changes to the standard (-1 hour)
  • second Sunday of March , daylight shift (your normal shift from GMT)

Consider a function in JavaScript that takes a Date parameter and needs to determine if the argument is standard or summer.

The root of the question:

  • How would you plot the date for the next time change?

Now the algorithm / pseudo-code is as follows:

  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 limitation here is to use the standard JavaScript function, and not to clear any parsing of the JavaScript Date object. This code will not run in the browser, so these great solutions will not apply.

** Not all places / regions in North America change time. *

+6
javascript algorithm datetime
source share
2 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 } 
+1
source share

1) I expect that different countries may have different rules. Some do not have daylight saving time. Thus, to find the answer in a specific locale, you can probably go through 365 (6) days to find the days when getTimetoneOffset() changes its value. This should not be a big lag in performance.

2) Then you can get a specific hour when the time changes (2 AM for the USA?). Suggest another cycle in 24 hours


PS: Well, someone has already completed the task =). You should check it before use (because I have not tested)

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

0
source share

All Articles