Compare two dates with JavaScript

Created by moonshadowLinked to 33m issues across 197 teams

tl;dr

Here's how to compare two dates using JavaScript. First, you will need to create a Date object for each date you want to compare. You can do this by using the Date constructor, which takes a date string as an argument. Once you have created the Date objects, you can use the comparison operators (>, <, <=, and >=) to compare the two dates.

However, if you want to check for equality, you will need to use the date.getTime() method of the Date object. This method returns the numeric value of the specified date as the number of milliseconds since January 1, 1970. You can then use the equality operators (==, !=, ===, and !==) to compare the dates. For example:

var d1 = new Date(); var d2 = new Date(d1); var same = d1.getTime() === d2.getTime(); var notSame = d1.getTime() !== d2.getTime();

Finally, it is important to note that it is best to use drop-downs or some other form of constrained date entry rather than text boxes, as this will help to avoid input validation issues.

We use cookies to personalize content
run ads, and analyze traffic.