I am trying to set the condition below to run Condition1 if new Date(visitationDate)
is equal to Date.now()
.
In the frontend the visitationDate come in as Thu Nov 11 2021 13:52:33 GMT 0100 (West Africa Standard Time)
and I convert it with a function to the format 2021-11-11T13:00:00.000Z
before sending it to the backend. I am using the date condition in my question in the backend. I can revert the conversion in the frontend if it will resolve my issue.
This is my current code used in the backend
if (new Date(visitationDate) == Date.now()) {
Condition1
} else {
Condition2
}
My question is how can I run Condition2 if the visitationDate is less than Date.now() or Date.now() is greater than visitationDate. I want to run Condition1 only if visitationDate is the current date or equal to Date.now() in a 24 hour window.
CodePudding user response:
Based on a previously submitted response that was deleted, I am using the getHours() method to normalize the date and checking if the difference is equal to zero. I tested with the current date and it returns true. When I tested with previous date and future date it returns false. Please note that users of my code have the same local time.
let d = new Date(visitationDate);
d.setHours(15, 0, 0, 0)
let now = new Date();
now.setHours(15, 0, 0, 0)
if (now-d == 0) {
Condition1
} else {
Condition2
}
CodePudding user response:
It seems that you want to compare dates without the time part, so convert the input timestamp to just a date and compare it to the current local date, e.g.
// Convert standard toString format to YYYY-MM-DD without changing the date
function reformatDate(s) {
// Parse string as UTC 0
let d = new Date(s.replace(/GMT\ .*/,'GMT 0000'));
// Return date only in ISO 8601 format
return d.toISOString().substring(0,10);
}
// Return date as local YYYY-MM-DD
function formatDate(d) {
return d.toLocaleDateString('en-CA');
}
let ts = 'Thu Nov 11 2021 13:52:33 GMT 0100 (West Africa Standard Time)';
// Date with some random time
let d = new Date(2021,10,11,23,59,59);
console.log(formatDate(d) ' : ' (reformatDate(ts) == formatDate(d)));
// Compare to today
d = new Date();
console.log(formatDate(d) ' : ' (reformatDate(ts) == formatDate(d)));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>