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?
js isDST() Function. It is used to check daylight saving time in Moment. js using the isDST() function. This function checks if the current moment is in daylight saving time.
The add function is used to add date and time to the moment object and the subtract function subtract date and time from the moment object. const moment = require('moment'); let now = moment(); console.
When Daylight Saving Time (DST) begins, we lose an hour. When it ends, we gain an hour.
The typical implementation of DST is to set clocks forward by one hour in the spring ("spring forward"), and to set clocks back by one hour in autumn ("fall back") to return to standard time. As a result, there is one 23-hour day in late winter or early spring and one 25-hour day in autumn.
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.
Here's how I made a little checker:
var curDst = dtdate.isDST()
var prevDst = moment(dtdate).clone().subtract(1, "day").isDST();
var nextDst = moment(dtdate).clone().add(1, "day").isDST();
var isDstChangeDate = (curDst !== nextDst) === true || (curDst === prevDst) !== true;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With