By Alex

2009-01-29 19:14:06 8 Comments

Can someone suggest a way to compare the values of two dates greater than, less than, and not in the past using JavaScript? The values will be coming from text boxes.


@William Hou 2020-01-31 17:27:06

All the above-given answers only solved one thing: compare two dates.

Indeed, they seem to be the answers to the question, but a big part is missing:

What if I want to check whether a person is fully 18 years old?

Unfortunately, NONE of the above-given answers would be able to answer that question.

For example, the current time (around the time when I started to type these words) is Fri Jan 31 2020 10:41:04 GMT-0600 (Central Standard Time), while a customer enters his Date of Birth as "01/31/2002".

If we use "365 days/year", which is "31536000000" milliseconds, we would get the following result:

       let currentTime = new Date();
       let customerTime = new Date(2002, 1, 31);
       let age = (currentTime.getTime() - customerTime.getTime()) / 31536000000
       console.log("age: ", age);

with the following print-out:

       age: 17.92724710838407

But LEGALLY, that customer is already 18 years old. Even he enters "01/30/2002", the result would still be

       age: 17.930039743467784

which is less than 18. The system would report the "under age" error.

And this would just keep going for "01/29/2002", "01/28/2002", "01/27/2002" ... "01/05/2002", UNTIL "01/04/2002".

A system like that would just kill all the customers who were born between 18 years 0 days and 18 years 26 days ago, because they are legally 18 years old, while the system shows "under age".

The following is an answer to a question like that:

invalidBirthDate: 'Invalid date. YEAR cannot be before 1900.',
invalidAge: 'Invalid age. AGE cannot be less than 18.',

public static birthDateValidator(control: any): any {
    const val = control.value;
    if (val != null) {
        const slashSplit = val.split('-');
        if (slashSplit.length === 3) {
            const customerYear = parseInt(slashSplit[0], 10);
            const customerMonth = parseInt(slashSplit[1], 10);
            const customerDate = parseInt(slashSplit[2], 10);
            if (customerYear < 1900) {
                return { invalidBirthDate: true };
            } else {
                const currentTime = new Date();
                const currentYear = currentTime.getFullYear();
                const currentMonth = currentTime.getMonth() + 1;
                const currentDate = currentTime.getDate();
                if (currentYear - customerYear < 18) {
                    return { invalidAge: true };
                } else if (
                    currentYear - customerYear === 18 &&
                    currentMonth - customerMonth < 0) {
                    return { invalidAge: true };
                } else if (
                    currentYear - customerYear === 18 &&
                    currentMonth - customerMonth === 0 &&
                    currentDate - customerDate < 0) {
                    return { invalidAge: true };
                } else {
                    return null;

@moonshadow 2009-01-29 19:20:10

The Date object will do what you want - construct one for each date, then compare them using the >, <, <= or >=.

The ==, !=, ===, and !== operators require you to use date.getTime() as in

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

to be clear just checking for equality directly with the date objects won't work

var d1 = new Date();
var d2 = new Date(d1);

console.log(d1 == d2);   // prints false (wrong!) 
console.log(d1 === d2);  // prints false (wrong!)
console.log(d1 != d2);   // prints true  (wrong!)
console.log(d1 !== d2);  // prints true  (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)

I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.

@patrick 2011-12-13 02:23:04

Even Ace's method is not failsafe. You need to reset the milliseconds first, and you might even want to reset the whole time. date1.setHours(0); date1.setMinutes(0); date1.setSeconds(0); date1.setMilliseconds(0); That combined with using .getTime() will give you an accurate compare result

@Karl 2012-11-16 21:32:02

@patrick, suggest calling setHours(0,0,0,0) this way. Eliminates the need for calling setMinutes() etc. Also, executes faster.

@Jason Sebring 2014-04-15 19:42:08

avoiding == or === to get desired result: now >= anotherNow && now <= anotherNow IS true FYI

@user2019515 2014-05-28 01:21:09

Why not simply use the toString() method on both dates and then compare with the == operator? Seems much easier than resetting the time and comparing afterwards, are there any drawbacks for this?

@superpuccio 2014-05-29 08:29:13

toString() doesn't work because two strings could be in this order: A < B but the related dates could be in this other order: A > B. For instance: stringA="Fri Jul 25 2014 00:00:00 GMT+0200", stringB="Mon Apr 21 2014 00:00:00 GMT+0200". As you can see the string A is less than string B (considering the lexicographic order) but date A is greater than date B (A refers July, B refers April).

@user2019515 2014-05-29 09:19:30

@superpuccio I was specifically talking about comparing with the == operator, not the other ones. I came to the conclusion that the toString method works great when comparing if the dates are exactly the same, if however you want to see if one event is on the same day as another event (different hours) then you have to reset the time first as said above.

@madprog 2014-11-06 13:56:10

You can also compare the numeric values of your dates in order to avoid comparing the objects themselves: date1.valueOf() == date2.valueOf()

@drevicko 2016-02-05 13:47:50

@patrick in the current answer, isn't d2 a clone of d1 (since d1 is passed to it's constructor), in which case they should be the same and not need resetting? ... or has the answer changed since your comment?

@patrick 2016-02-08 14:31:53

@drevicko, no, it's not a clone... d2 is an object that's initialized with the same DATE as d1, the time is the current time, so Karl's method (setHours(0,0,0,0)) is even better, you need to reset the time to make d1 equal to d2!

@Nicholas 2016-05-19 16:53:29

@madprog date.valueOf() is a beautifully simple solution that works perfectly for our purposes. Thanks MadProg!

@Filip Cornelissen 2016-07-04 10:10:27

if you use .setHours(0,0,0,0) you also eliminate the need for .getTime() eg: console.log(d1.setHours(0,0,0,0) === d2.setHours(0,0,0,0)); // prints true (correct)

@user2696258 2017-08-02 03:32:10

Is it safe to convert the String to Date object? Can that not throw exception or give unreliable results? What can be the most reliable way of doing comaring dates in JS? When you say unreliable results, can this method give different/wrong values even when we are sure the the date format will not change --> It would be "Thursday, 10 Aug 2017". Your help here is very much appreciated.

@student0495 2017-08-22 08:50:11

Very well explained, also for more examples you can check w3schools or the actual documentation

@chharvey 2017-11-09 15:37:14

you could use the property of antisymmetry: (d1 <= d2) && (d1 >= d2) implies d1 "equals" d2

@Jo. 2017-11-17 18:19:10

Be careful if you create the date with different string formats. When I created one date with var d1 = new Date("2011-11-11"); and another with var d2 = new Date("11 Nov 2011"); the first one included time information, while the second did not, so comparisons that seemed like they should work did not.

@abyrne85 2018-11-23 12:35:38

Is it possible to compare days only - ignoring time of day

@Pierrick Martellière 2019-08-13 09:25:29

Saved me valuable time. Thanks.

@TmTron 2019-09-06 09:17:58

And the reason why the relational operators (<, <=, >, >= ) comparison works, is that Javascript calls valueOf before the comparison is made: and for a Date object valueOfreturns the number of milliseconds since the Unix Epoch.This is not the case for equality comparison

@MICHAEL PRABHU 2019-06-28 06:47:49

The simple way is,

var first = '2012-11-21';
var second = '2012-11-03';

if (new Date(first) > new Date(second) {

@Peter Wilkinson 2011-11-01 00:48:12

By far the easiest method is to subtract one date from the other and compare the result.

var oDateOne = new Date();
var oDateTwo = new Date();

alert(oDateOne - oDateTwo === 0);
alert(oDateOne - oDateTwo < 0);
alert(oDateOne - oDateTwo > 0);

@Alireza 2017-07-11 09:59:46

Comparing dates in JavaScript is quite easy... JavaScript has built-in comparison system for dates which makes it so easy to do the comparison...

Just follow these steps for comparing 2 dates value, for example you have 2 inputs which each has a Date value in String and you to compare them...

1. you have 2 string values you get from an input and you'd like to compare them, they are as below:

var date1 = '01/12/2018';
var date2 = '12/12/2018';

2. They need to be Date Object to be compared as date values, so simply convert them to date, using new Date(), I just re-assign them for simplicity of explanation, but you can do it anyway you like:

date1 = new Date(date1);
date2 = new Date(date2);

3. Now simply compare them, using the > < >= <=

date1 > date2;  //false
date1 < date2;  //true
date1 >= date2; //false
date1 <= date2; //true

compare dates in javascript

@Joshua Oglesbee 2018-05-24 13:47:48

I found that most solutions for comparing dates work in any browser. The issue I experienced was with IE. This solution worked across the board. Thx Alireza!

@maxisam 2018-07-26 15:41:58

It doesn't work. And it shouldn't work. You are comparing date object.

@humanityANDpeace 2018-12-08 09:16:25

@maxisam No, it does work because of comparison operators (<,>,<=,>=) being used, the Date objects are converted first to unix epoch (seconds), and it works fine. However this might lead to the common mistake of doing date1 == date2 where indeed an error is introduced as not the value but the instance equality is checked. To prevent this and check for equality of the date value this would work : date1.valueOf() == date2.valueOf() , or shorter date1+0 == date2+0

@AaA 2020-02-18 03:51:05

Note from MDN Note: Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies. and Note: Parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

@Razan Paul 2016-07-05 05:53:00

Via Moment.js


function compare(dateTimeA, dateTimeB) {
    var momentA = moment(dateTimeA,"DD/MM/YYYY");
    var momentB = moment(dateTimeB,"DD/MM/YYYY");
    if (momentA > momentB) return 1;
    else if (momentA < momentB) return -1;
    else return 0;

alert(compare("11/07/2015", "10/07/2015"));

The method returns 1 if dateTimeA is greater than dateTimeB

The method returns 0 if dateTimeA equals dateTimeB

The method returns -1 if dateTimeA is less than dateTimeB

@amb 2018-05-18 12:51:14

There's no need to use an external library such as Moment to perform date comparison for Date objects.

@razorsyntax 2018-12-15 17:15:15

Moment was absolutely necessary for my use case. Thank you, Razan!

@svarog 2018-12-30 14:14:00

why are you even using < or > operators when moment already comes with handy comparison methods such as .isBefore and .isAfter, it's all in the docs

@Jason S 2009-01-29 19:19:21

what format?

If you construct a Javascript Date object, you can just subtract them to get a milliseconds difference (edit: or just compare them) :

js>t1 = new Date()
Thu Jan 29 2009 14:19:28 GMT-0500 (Eastern Standard Time)
js>t2 = new Date()
Thu Jan 29 2009 14:19:31 GMT-0500 (Eastern Standard Time)
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)

@devios1 2012-12-05 01:15:18

Subtracting is a good idea as it avoids the == comparison problem mentioned above.

@hyde 2014-03-07 21:03:52

What JavaScript REPL are you using?

@Jason S 2014-03-07 22:31:29

JSDB -- see -- I use it less often these days now that Python is my language of choice, but it's still a great utility.

@Jason S 2015-06-05 12:44:00

@StuartP.Bentley I don't know, because I don't use any of them. I use jsdb.

@pcarvalho 2016-03-26 01:20:55

when going through a large amount of dates, this seems most efficient because there's no need to convert with getTime().

@vickisys 2015-05-06 11:25:28

var date_today=new Date();
var formated_date = formatDate(date_today);//Calling formatDate Function

var input_date="2015/04/22 11:12 AM";

var currentDateTime = new Date(Date.parse(formated_date));
var inputDateTime   = new Date(Date.parse(input_date));

if (inputDateTime <= currentDateTime){
    //Do something...

function formatDate(date) {
    var hours = date.getHours();
    var minutes = date.getMinutes();
    var ampm = hours >= 12 ? 'PM' : 'AM';

    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    hours   = hours < 10 ? '0'+hours : hours ;

    minutes = minutes < 10 ? '0'+minutes : minutes;

    var strTime = hours+":"+minutes+ ' ' + ampm;
    return  date.getFullYear()+ "/" + ((date.getMonth()+1) < 10 ? "0"+(date.getMonth()+1) :
    (date.getMonth()+1) ) + "/" + (date.getDate() < 10 ? "0"+date.getDate() :
    date.getDate()) + " " + strTime;

@bbsimonbb 2017-10-20 09:51:47


A javascript date has no notion of timezone. It's a moment in time (ticks since the epoch) with handy functions for translating to and from strings in the "local" timezone. If you want to work with dates using date objects, as everyone here is doing, you want your dates to represent UTC midnight at the start of the date in question. This is a common and necessary convention that lets you work with dates regardless of the season or timezone of their creation. So you need to be very vigilant to manage the notion of timezone, particularly when you create your midnight UTC Date object.

Most of the time, you will want your date to reflect the timezone of the user. Click if today is your birthday. Users in NZ and US click at the same time and get different dates. In that case, do this...

// create a date (utc midnight) reflecting the value of myDate and the environment's timezone offset.
new Date(Date.UTC(myDate.getFullYear(),myDate.getMonth(), myDate.getDate()));

Sometimes, international comparability trumps local accuracy. In that case, do this...

// the date in London of a moment in time. Device timezone is ignored.
new Date(Date.UTC(myDate.getUTCYear(), myDate.getyUTCMonth(), myDate.getUTCDate()));

Now you can directly compare your date objects as the other answers suggest.

Having taken care to manage timezone when you create, you also need to be sure to keep timezone out when you convert back to a string representation. So you can safely use...

  • toISOString()
  • getUTCxxx()
  • getTime() //returns a number with no time or timezone.
  • .toLocaleDateString("fr",{timezone:"UTC"}) // whatever locale you want, but ALWAYS UTC.

And totally avoid everything else, especially...

  • getYear(),getMonth(),getDate()

@Bachas 2017-09-20 11:11:40

You can date compare as most simple and understandable way like.

<input type="date" id="getdate1" />
<input type="date" id="getdate2" />

let suppose you have two date input you want to compare them.

so firstly write a common method to parse date.

 <script type="text/javascript">
            function parseDate(input) {
             var datecomp= input.split('.'); //if date format 21.09.2017

              var tparts=timecomp.split(':');//if time also giving
              return new Date(dparts[2], dparts[1]-1, dparts[0], tparts[0], tparts[1]);
// here new date(  year, month, date,)

parseDate() is the make common method for parsing the date. now you can checks your date =, > ,< any type of compare

    <script type="text/javascript">

              //parseDate(pass in this method date);
                    Var Date1=parseDate($("#getdate1").val());
                        Var Date2=parseDate($("#getdate2").val());
               //use any oe < or > or = as per ur requirment 
               if(Date1 = Date2){
         return false;  //or your code {}

For Sure this code will help you.

@Yukulélé 2012-11-15 09:54:18

Subtract two date get the difference in millisecond, if you get 0 it's the same date

function areSameDate(d1, d2){
    return d1 - d2 === 0

@user4439128 2017-06-15 12:42:21

try this while compare date should be iso format "yyyy-MM-dd" if you want to compare only dates use this datehelper

<a href=""> Live Demo</a>

@Sanjeev Singh 2017-03-14 17:10:14

Note - Compare Only Date Part:

When we compare two date in javascript. It takes hours, minutes and seconds also into consideration.. So If we only need to compare date only, this is the approach:

var date1= new Date("01/01/2014").setHours(0,0,0,0);

var date2= new Date("01/01/2014").setHours(0,0,0,0);

Now: if date1.valueOf()> date2.valueOf() will work like a charm.

@Mina Gabriel 2013-08-02 21:06:16


Here is a function that return {boolean} if the from dateTime > to dateTime Demo in action

var from = '08/19/2013 00:00'
var to = '08/12/2013 00:00 '

function isFromBiggerThanTo(dtmfrom, dtmto){
   return new Date(dtmfrom).getTime() >=  new Date(dtmto).getTime() ;
console.log(isFromBiggerThanTo(from, to)); //true



var date_one = '2013-07-29 01:50:00',
date_two = '2013-07-29 02:50:00';
//getTime() returns the number of milliseconds since 01.01.1970.
var timeStamp_date_one = new Date(date_one).getTime() ; //1375077000000 
console.log(typeof timeStamp_date_one);//number 
var timeStamp_date_two = new Date(date_two).getTime() ;//1375080600000 
console.log(typeof timeStamp_date_two);//number 

since you are now having both datetime in number type you can compare them with any Comparison operations

( >, < ,= ,!= ,== ,!== ,>= AND <=)


if you are familiar with C# Custom Date and Time Format String this library should do the exact same thing and help you format your date and time dtmFRM whether you are passing in date time string or unix format


var myDateTime = new dtmFRM();

alert(myDateTime.ToString(1375077000000, "MM/dd/yyyy hh:mm:ss ampm"));
//07/29/2013 01:50:00 AM

alert(myDateTime.ToString(1375077000000,"the year is yyyy and the day is dddd"));
//this year is 2013 and the day is Monday

alert(myDateTime.ToString('1/21/2014', "this month is MMMM and the day is dd"));
//this month is january and the day is 21


all you have to do is passing any of these format pacified in the library js file

@Mina Gabriel 2014-10-09 17:23:45

new Date(dtmfrom) >= new Date(dtmto) is much slower than new Date(dtmfrom).getTime() >= new Date(dtmto).getTime()

@RobG 2014-10-09 23:09:12

Perhaps, but the difference is around 30 to 120 nanoseconds (say 0.000000075 seconds) per operation, depending on the browser, so not really significant.

@yoniLavi 2016-11-09 18:22:28

Another way to compare two dates, is through the toISOString() method. This is especially useful when comparing to a fixed date kept in a string, since you can avoid creating a short-lived object. By virtue of the ISO 8601 format, you can compare these strings lexicographically (at least when you're using the same timezone).

I'm not necessarily saying that it's better than using time objects or timestamps; just offering this as another option. There might be edge cases when this could fail, but I haven't stumbled upon them yet :)

@Salahin Rocky 2016-08-31 17:00:39

To compare two date we can use date.js JavaScript library which can be found at :

and use the Date date1, Date date2 ) method and it return a number which mean the following result:

-1 = date1 is lessthan date2.

0 = values are equal.

1 = date1 is greaterthan date2.

@Qasim 2016-04-08 13:45:34

Hi Here is my code to compare dates . In my case i am doing a check to not allow to select past dates.

var myPickupDate = <pick up date> ;
var isPastPickupDateSelected = false;
var currentDate = new Date();

if(currentDate.getFullYear() <= myPickupDate.getFullYear()){
    if(currentDate.getMonth()+1 <= myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
                        if(currentDate.getDate() <= myPickupDate.getDate() || currentDate.getMonth()+1 < myPickupDate.getMonth()+1 || currentDate.getFullYear() < myPickupDate.getFullYear()){
                                            isPastPickupDateSelected = false;
console.log("cannot select past pickup date");
isPastPickupDateSelected = true;

@some 2009-01-31 00:18:07

The easiest way to compare dates in javascript is to first convert it to a Date object and then compare these date-objects.

Below you find an object with three functions:


    Returns a number:

    • -1 if a < b
    • 0 if a = b
    • 1 if a > b
    • NaN if a or b is an illegal date
  • dates.inRange (d,start,end)

    Returns a boolean or NaN:

    • true if d is between the start and end (inclusive)
    • false if d is before start or after end.
    • NaN if one or more of the dates are illegal.
  • dates.convert

    Used by the other functions to convert their input to a date object. The input can be

    • a date-object : The input is returned as is.
    • an array: Interpreted as [year,month,day]. NOTE month is 0-11.
    • a number : Interpreted as number of milliseconds since 1 Jan 1970 (a timestamp)
    • a string : Several different formats is supported, like "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
    • an object: Interpreted as an object with year, month and date attributes. NOTE month is 0-11.


// Source:
var dates = {
    convert:function(d) {
        // Converts the date in d to a date-object. The input can be:
        //   a date object: returned without modification
        //  an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
        //   a number     : Interpreted as number of milliseconds
        //                  since 1 Jan 1970 (a timestamp) 
        //   a string     : Any format supported by the javascript engine, like
        //                  "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
        //  an object     : Interpreted as an object with year, month and date
        //                  attributes.  **NOTE** month is 0-11.
        return (
            d.constructor === Date ? d :
            d.constructor === Array ? new Date(d[0],d[1],d[2]) :
            d.constructor === Number ? new Date(d) :
            d.constructor === String ? new Date(d) :
            typeof d === "object" ? new Date(d.year,d.month, :
    compare:function(a,b) {
        // Compare two dates (could be of any type supported by the convert
        // function above) and returns:
        //  -1 : if a < b
        //   0 : if a = b
        //   1 : if a > b
        // NaN : if a or b is an illegal date
        // NOTE: The code inside isFinite does an assignment (=).
        return (
            isFinite(a=this.convert(a).valueOf()) &&
            isFinite(b=this.convert(b).valueOf()) ?
            (a>b)-(a<b) :
    inRange:function(d,start,end) {
        // Checks if date in d is between dates in start and end.
        // Returns a boolean or NaN:
        //    true  : if d is between start and end (inclusive)
        //    false : if d is before start or after end
        //    NaN   : if one or more of the dates is illegal.
        // NOTE: The code inside isFinite does an assignment (=).
       return (
            isFinite(d=this.convert(d).valueOf()) &&
            isFinite(start=this.convert(start).valueOf()) &&
            isFinite(end=this.convert(end).valueOf()) ?
            start <= d && d <= end :

@nktssh 2015-05-14 09:26:17

(a > b) - (a < b) is useful for sorting dates array

@some 2015-05-14 10:37:57

@nikita Yes it is, and a function that returns that result can be used with Array.prototype.sort as long as all values are valid dates. If there could be invalid dates, I recommend using something like function ( a, b ) { a = a === undefined || a === null : NaN : a.valueOf( a ); b = a === undefined || b === null : NaN : a.valueOf( b ); return isFinite( a ) && isFinite( b ) ? ( a > b ) - ( a < b ) : NaN; }

@RobG 2016-08-17 23:05:39

@nktssh—maybe, but return a - b is simpler and replaces the entire return statement.

@mpen 2013-09-27 15:38:23

Compare day only (ignoring time component):

Date.prototype.sameDay = function(d) {
  return this.getFullYear() === d.getFullYear()
    && this.getDate() === d.getDate()
    && this.getMonth() === d.getMonth();


if(date1.sameDay(date2)) {
    // highlight day on calendar or something else clever

@Paresh3489227 2016-08-09 07:07:22

this is good. but what if i compare nextDay or previousDay. i tried this Date.prototype.nextDay = function(d) { return this.getFullYear() === d.getFullYear() && this.getDate() < d.getDate() && this.getMonth() === d.getMonth(); } Date.prototype.previousDay = function(d) { return this.getFullYear() === d.getFullYear() && this.getDate() > d.getDate() && this.getMonth() === d.getMonth(); } but it will work only in this month only. how do i compare across month or across years

@Salman A 2013-01-31 16:04:16

The relational operators < <= > >= can be used to compare JavaScript dates:

var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 2);
d1 <  d2; // true
d1 <= d2; // true
d1 >  d2; // false
d1 >= d2; // false

However, the equality operators == != === !== cannot be used to compare (the value of) dates because:

  • Two distinct objects are never equal for either strict or abstract comparisons.
  • An expression comparing Objects is only true if the operands reference the same Object.

You can compare the value of dates for equality using any of these methods:

var d1 = new Date(2013, 0, 1);
var d2 = new Date(2013, 0, 1);
 * note: d1 == d2 returns false as described above
d1.getTime() == d2.getTime(); // true
d1.valueOf() == d2.valueOf(); // true
Number(d1)   == Number(d2);   // true
+d1          == +d2;          // true

Both Date.getTime() and Date.valueOf() return the number of milliseconds since January 1, 1970, 00:00 UTC. Both Number function and unary + operator call the valueOf() methods behind the scenes.

@user2696258 2017-08-02 03:33:29

Is it safe to convert the String to Date object? Can that not throw exception or give unreliable results? What can be the most reliable way of doing comaring dates in JS? When you say unreliable results, can this method give different/wrong values even when we are sure the the date format will not change --> It would be "Thursday, 10 Aug 2017". Your help here is very much appreciated.

@user2696258 2017-08-02 03:34:16

Can this give unreliable results for same date value on different OS/browsers/devices?

@Salman A 2017-08-02 07:00:12

@user2696258 this is the most reliable way of comparing two Date objects. Converting a string to date is a different issue... use a date parsing library or roll your own solution. Thursday, 10 Aug 2017 is non-standard format and different browsers might parse it differently, or not parse it at all. See notes on Date.parse.

@hex494D49 2014-06-23 22:22:18

Let's suppose that you deal with this 2014[:-/.]06[:-/.]06 or this 06[:-/.]06[:-/.]2014 date format, then you may compare dates this way

var a = '2014.06/07', b = '2014-06.07', c = '07-06/2014', d = '07/06.2014';

parseInt(a.replace(/[:\s\/\.-]/g, '')) == parseInt(b.replace(/[:\s\/\.-]/g, '')); // true
parseInt(c.replace(/[:\s\/\.-]/g, '')) == parseInt(d.replace(/[:\s\/\.-]/g, '')); // true
parseInt(a.replace(/[:\s\/\.-]/g, '')) < parseInt(b.replace(/[:\s\/\.-]/g, '')); // false
parseInt(c.replace(/[:\s\/\.-]/g, '')) > parseInt(d.replace(/[:\s\/\.-]/g, '')); // false

As you can see, we strip separator(s) and then compare integers.

@Paul 2014-03-26 15:41:05

Just to add yet another possibility to the many existing options, you could try:

if (date1.valueOf()==date2.valueOf()) .....

...which seems to work for me. Of course you do have to ensure that both dates are not undefined...

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():0) .....

This way we can ensure that a positive comparison is made if both are undefined also, or...

if ((date1?date1.valueOf():0)==(date2?date2.valueOf():-1) .....

...if you prefer them not to be equal.

@iinvole 2014-01-30 04:42:01

Try using this code

var f =date1.split("/");

var t =date2.split("/");

var x =parseInt(f[2]+f[1]+f[0]);

var y =parseInt(t[2]+t[1]+t[0]);

if(x > y){
    alert("date1 is after date2");

else if(x < y){
    alert("date1 is before date2");

    alert("both date are same");

@Isochronous 2014-12-19 16:06:29

There's absolutely no reason to do string splitting on a date like that when you can just use the getMinutes, getSeconds, etc methods.

@Isochronous 2015-02-09 17:06:59

Why the hell do I keep losing reputation when this answer gets downvoted?

@Júlio Paulillo 2013-10-24 17:34:25

Before comparing the Dates object, try setting both of their milliseconds to zero like Date.setMilliseconds(0);.

In some cases where the Date object is dynamically created in javascript, if you keep printing the Date.getTime(), you'll see the milliseconds changing, which will prevent the equality of both dates.

@Brijesh 2013-09-20 15:37:31

Here is what I did in one of my projects,

function CompareDate(tform){
     var startDate = new Date(document.getElementById("START_DATE").value.substring(0,10));
     var endDate = new Date(document.getElementById("END_DATE").value.substring(0,10));

         var estStartDate = tform.START_DATE.value;
         //format for Oracle
         tform.START_DATE.value = estStartDate + " 00:00:00";

         var estEndDate = tform.END_DATE.value;
         //format for Oracle
         tform.END_DATE.value = estEndDate + " 00:00:00";

     if(endDate <= startDate){
         alert("End date cannot be smaller than or equal to Start date, please review you selection.");
         tform.START_DATE.value = document.getElementById("START_DATE").value.substring(0,10);
         tform.END_DATE.value = document.getElementById("END_DATE").value.substring(0,10);
         return false;

calling this on form onsubmit. hope this helps.

@Daniel Lidström 2013-05-23 12:21:09

Compare < and > just as usual, but anything involving = should use a + prefix. Like so:

var x = new Date('2013-05-23');
var y = new Date('2013-05-23');

// less than, greater than is fine:
x < y; => false
x > y; => false
x === y; => false, oops!

// anything involving '=' should use the '+' prefix
// it will then compare the dates' millisecond values
+x <= +y;  => true
+x >= +y;  => true
+x === +y; => true

Hope this helps!

@huysentruitw 2013-12-12 09:56:13

terribly slow :) I prefer x.getTime() === y.getTime() method, both readable and extremely fast see jsperf

@Salman A 2014-01-20 09:30:19

The + operator attempts to convert the expression into a Number. Date.valueOf() is used for the conversion (which returns the same thing as Date.getTime().

@Eloims 2014-12-17 16:48:51

@WouterHuysentruit Both are very fast (> 3 Millions OPS in the slowest browser). Use the method you think is more readable

@Salman A 2015-03-16 10:52:36

Note that anything involving '=' should use the '+' prefix part of your answer is incorrect. <, <=, > and >= use the same algorithm (abstract relational comparison algorithm) behind the scenes.

@Neri 2017-03-19 12:46:42

This worked for me without even the + sign. I don't know why.

@catamphetamine 2017-05-16 21:26:23

Your answer is wrong, both >= and <= do work without an extra +

@user2696258 2017-08-02 03:33:17

Is it safe to convert the String to Date object? Can that not throw exception or give unreliable results? What can be the most reliable way of doing comaring dates in JS? When you say unreliable results, can this method give different/wrong values even when we are sure the the date format will not change --> It would be "Thursday, 10 Aug 2017". Your help here is very much appreciated.

@Gyuhyeon Lee 2019-06-24 06:09:56… Thanks to your answer, the service I develop at work had a terrible bug that were hard to track.

@stay_hungry 2012-08-09 10:49:00

you use this code,

var firstValue = "2012-05-12".split('-');
var secondValue = "2014-07-12".split('-');

 var firstDate=new Date();
 firstDate.setFullYear(firstValue[0],(firstValue[1] - 1 ),firstValue[2]);

 var secondDate=new Date();
 secondDate.setFullYear(secondValue[0],(secondValue[1] - 1 ),secondValue[2]);     

  if (firstDate > secondDate)
   alert("First Date  is greater than Second Date");
    alert("Second Date  is greater than First Date");

And also check this link

@Mathias Lykkegaard Lorenzen 2013-03-08 19:44:57

A reason not to refer to W3Schools: - nice solution though - is it standards compliant, and does it work in all browsers?

@Daniel Lidström 2013-06-13 12:35:42

Better refer to Mozilla Developer Network:….

@user1931504 2013-02-12 10:31:13

var curDate=new Date();
var startDate=document.forms[0].m_strStartDate;

var endDate=document.forms[0].m_strEndDate;
var startDateVal=startDate.value.split('-');
var endDateVal=endDate.value.split('-');
var firstDate=new Date();
firstDate.setFullYear(startDateVal[2], (startDateVal[1] - 1), startDateVal[0]);

var secondDate=new Date();
secondDate.setFullYear(endDateVal[2], (endDateVal[1] - 1), endDateVal[0]);
if(firstDate > curDate) {
    alert("Start date cannot be greater than current date!");
    return false;
if (firstDate > secondDate) {
    alert("Start date cannot be greater!");
    return false;

@Pravesh Hajela 2011-04-16 11:30:40

Dates comparison:

var str1  = document.getElementById("Fromdate").value;
var str2  = document.getElementById("Todate").value;
var dt1   = parseInt(str1.substring(0,2),10); 
var mon1  = parseInt(str1.substring(3,5),10);
var yr1   = parseInt(str1.substring(6,10),10); 
var dt2   = parseInt(str2.substring(0,2),10); 
var mon2  = parseInt(str2.substring(3,5),10); 
var yr2   = parseInt(str2.substring(6,10),10); 
var date1 = new Date(yr1, mon1, dt1); 
var date2 = new Date(yr2, mon2, dt2); 

if(date2 < date1)
   alert("To date cannot be greater than from date");
   return false; 
   alert("Submitting ...");

@urbanhusky 2015-11-13 15:08:46

There are so many things that don't fit the question and make (bad) assumptions: Reading a (localized) date representation from an HTML-element, splitting these string-representations into the separate components by using a very optimistic extraction method; creating new dates based on the data (which might be invalid); not using time; failing if date 2 is before date 1 - but succeeding if it is equal or greater - not mentioning how dates can actually be compared.

@jwchang 2012-08-22 01:40:14

I usually store Dates as timestamps(Number) in databases.

When I need to compare, I simply compare among those timestamps or

convert it to Date Object and then compare with > <if necessary.

Note that == or === does not work properly unless your variables are references of the same Date Object.

Convert those Date objects to timestamp(number) first and then compare equality of them.

Date to Timestamp

var timestamp_1970 = new Date(0).getTime(); // 1970-01-01 00:00:00
var timestamp = new Date().getTime(); // Current Timestamp

Timestamp to Date

var timestamp = 0; // 1970-01-01 00:00:00
var DateObject = new Date(timestamp);

@Scott Stensland 2015-10-26 20:06:22

This is the best answer - and the fastest

Related Questions

Sponsored Content

9 Answered Questions

[SOLVED] Why is subtracting these two times (in 1927) giving a strange result?

  • 2011-07-27 08:15:58
  • Freewind
  • 643707 View
  • 6737 Score
  • 9 Answer
  • Tags:   java date timezone

95 Answered Questions

[SOLVED] How to remove specific item from array?

  • 2011-04-23 22:17:18
  • Walker
  • 6348549 View
  • 7931 Score
  • 95 Answer
  • Tags:   javascript arrays

4 Answered Questions

53 Answered Questions

[SOLVED] How do I get the current date in JavaScript?

  • 2009-10-07 11:39:02
  • Suresh Chaganti
  • 2603100 View
  • 2234 Score
  • 53 Answer
  • Tags:   javascript date

86 Answered Questions

[SOLVED] How do JavaScript closures work?

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

38 Answered Questions

[SOLVED] var functionName = function() {} vs function functionName() {}

67 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

38 Answered Questions

[SOLVED] How do you get a timestamp in JavaScript?

13 Answered Questions

[SOLVED] event.preventDefault() vs. return false

Sponsored Content