Home > Article > Web Front-end > How to Compare Dates in JavaScript Without Time?
You're attempting to compare two dates while ignoring the time component. However, your code seems to be incorrect. Let's examine your code and find a solution.
if (userDate > now)
In this comparison, you're comparing the entire Date objects, including their time components. This can lead to incorrect results, especially if the two dates have different times but same day and month.
To focus solely on the date part, you can zero out the time components of the Date objects. This can be achieved using the setHours method with 0 values for hours, minutes, seconds, and milliseconds.
Here's an adjusted version of your code:
var userDate = new Date(); userDate.setFullYear(dateArray[2], userMonth, dateArray[0], 0, 0, 0, 0); var now = new Date(); now.setHours(0, 0, 0, 0); if (userDate > now)
Now, the comparison will evaluate only the date part of the Date objects, disregarding the time component. This should provide you with the desired outcome when checking if userDate is greater than now.
The above is the detailed content of How to Compare Dates in JavaScript Without Time?. For more information, please follow other related articles on the PHP Chinese website!