Home  >  Article  >  Web Front-end  >  How to Compare Dates in JavaScript Without Time?

How to Compare Dates in JavaScript Without Time?

DDD
DDDOriginal
2024-11-12 00:35:02938browse

How to Compare Dates in JavaScript Without Time?

Comparing Dates without Time in JavaScript

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn