In JavaScript, you can use the Date.prototype.toDateString()
method to compare two dates for equality, which returns a string representation of the date in the format "Day Month Date Year". By comparing the string representations of the dates, you can check if they represent the same day or not.
For example:
const date1 = new Date('2023-03-23'); const date2 = new Date('2023-03-23'); console.log(date1); // 'Thu Mar 23 2023' console.log(date2); // 'Thu Mar 23 2023' console.log(date1.toDateString() === date2.toDateString()); // true
Please note that comparing two Date
objects directly using the equality operator (===
) in JavaScript compares object references, and not the actual dates. Therefore, as suggested, you should compare the string representation of the dates instead to check if two dates are in fact the same.
If time is specified in the dates, the Date.prototype.toDateString()
method will still work correctly as it ignores the time part and only compares the date portion:
const date1 = new Date('2023-03-23T10:00:00Z'); const date2 = new Date('2023-03-23T18:00:00Z'); console.log(date1); // 'Thu Mar 23 2023' console.log(date2); // 'Thu Mar 23 2023' console.log(date1.toDateString() === date2.toDateString()); // true
Hope you found this post useful. It was published . Please show your love and support by sharing this post.