How do I do a Date comparison in Javascript? [duplicate]

I would like to compare two dates in javascript. I have been doing some research, but all I can find is how to return the current date. I want to compare 2 separate dates, not related to today. How do I do that.

var startDate = Date(document.form1.Textbox2);

if (date1.getTime() > date2.getTime()) {
    alert("The first date is after the second date!");
}

Reference to Date object


new Date('1945/05/09').valueOf() < new Date('2011/05/09').valueOf()

JavaScript's dates can be compared using the same comparison operators the rest of the data types use: >, <, <=, >=, ==, !=, ===, !==.

If you have two dates A and B, then A < B if A is further back into the past than B.

But it sounds like what you're having trouble with is turning a string into a date. You do that by simply passing the string as an argument for a new Date:

var someDate = new Date("12/03/2008");

or, if the string you want is the value of a form field, as it seems it might be:

var someDate = new Date(document.form1.Textbox2.value);

Should that string not be something that JavaScript recognizes as a date, you will still get a Date object, but it will be "invalid". Any comparison with another date will return false. When converted to a string it will become "Invalid Date". Its getTime() function will return NaN, and calling isNaN() on the date itself will return true; that's the easy way to check if a string is a valid date.


You can use the getTime() method on a Date object to get the timestamp (in milliseconds) relative to January 1, 1970. If you convert your two dates into integer timestamps, you can then compare the difference by subtracting them. The result will be in milliseconds so you just divide by 1000 for seconds, then 60 for minutes, etc.