I have a function where user selects dates and it gets stored in an array object.
There is check to see if user does not select dates that are already passed.
It should ideally allow user to select current date but when I do so it is not working and the check gets triggered.
datesArr = [{ date: '05/10/2023' }, { date: '05/11/2023' }];
let result = datesArr.every(({ date }) => {
return new Date(date).toLocaleDateString() < new Date().toLocaleDateString();
});
console.log(result);
result === false ? promptMessages(`Cannot use an older date.`, 'error') : '';
So as per the array, the dates selected by the user should be valid, instead I get the result as false.
I only need to match dates, so time is not relevant.
How do I ensure the current date is not treated as an old date.
3
Answers
You can use the toISOString but you need to consolidate. If I run the script in my timezone, the 10th at midnight becomes the 9th
Example
Instead of comparing the result of
toLocaleDateString()
, I would compare the integer value usingvalueOf
MDN page for Date.valueOf.Your code would look like this:
The issues with the code you have written is
new Date(date).toLocaleDateString() < new Date().toLocaleDateString()
this will convert your date to a sting and you are converting the strings there, that’s incorrect. you cant compare two strings and see the date is greater or lessAlso you have to see if the date is not a past date, sees like you have used the comparison operator incorrectly.
The logic I did is
getTime
of that date.JavaScript
getTime
will return the number of milliseconds for this date since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC. In the time values that we are comparing its against two particular date which has time 00:00:00. Its enough to compare these two times in your case.Working Fiddle