I'm working on code to determine if the current local datetime falls within a datetime range, a start and end datetime.
I start by getting the start and end datetime values as a serialized GMT string (this is what the source system is returning to me):
let myStartDate = "2020-09-11T14:15:13.000Z";
let myEndDate = "2020-09-15T01:09:34.000Z";
I then convert the datetime to UTC format:
let startDate = new Date(myStartDate).toUTCString();
let endDate = new Date(myEndDate).toUTCString();
let now = new Date().toUTCString();
Then I check to see if now
is between the startDate
and endDate
:
if (now > startDate && now < endDate) {
console.log("You're INSIDE the datetime window!");
} else {
console.log("You're OUTSIDE the datetime window!");
}
console.log("Now: " + new Date(now));
console.log("Start: " + new Date(startDate));
console.log("End: " + new Date(endDate));
When I run this, my code is telling me I'm outside the datetime window, even though the start and datetime values are a couple days before and after my current datetime.
An alternative I see is using getTime()
, which converts the datetime to a UTC milliseconds number.
let startDate = new Date(myStartDate).getTime();
let endDate = new Date(myEndDate).getTime();
let now = new Date().getTime();
This seems to work, but I'm confused why toUTCString()
can't be evaluated the same way.