Moment.js - How To Detect Daylight Savings Time And Add One Day

date, javascript, momentjs

Solution

To detect DST, use the `.isDST()` method: http://momentjs.com/docs/#/query/is-daylight-saving-time/

moment([2011, 2, 12]).isDST(); // false, March 12 2011 is not DST
moment([2011, 2, 14]).isDST(); // true, March 14 2011 is DST

Using this test, you should be able to determine how to modify your program's behavior accordingly.

Problem

I need to create Date Objects from strings of Date data for every hour of every day since the year 2000. The strings look like this for every hour, in a `Month/Day/Year Hour` format... ``` "04/02/2000 01", "04/02/2000 02", "04/02/2000 03" ...all the way to... "04/02/2000 24" ``` Now, I have the following code, which works fine except for on days with Daylight Savings Time... ``` // Split At Space var splitDate = "04/02/2000 24".split(/[ ]+/); var hour = splitDate[1]; var day = splitDate[0]; // Split At Slashes var dayArray = day.split("/"); if (hour === "24") { // Months are zero-based, so subtract 1 from the month date = new Date(Date.UTC( dayArray[2], parseInt(dayArray[0] - 1), dayArray[1], 0, 0, 0 )); date.setDate(date.getDate() + 1); } else { // Months and Hours are zero-based, so subtract 1 from each date = new Date(Date.UTC( dayArray[2], parseInt(dayArray[0] - 1), dayArray[1], hour, 0, 0 )); }; ``` On days with daylight savings time, like `04/02/2000` adding a day does not work if the hour is `24`. Instead, it just returns `Sun, 02 Apr 2000 23:00:00 GMT` With Moment.js, is it possible to detect a DST day and get this code to work correctly?

Original source