[javascript] Compare two dates with JavaScript

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.

This question is related to javascript date datetime compare

The answer is


function datesEqual(a, b)
{
   return (!(a>b || b>a))
}

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>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true

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

_x000D_
_x000D_
var oDateOne = new Date();_x000D_
var oDateTwo = new Date();_x000D_
_x000D_
alert(oDateOne - oDateTwo === 0);_x000D_
alert(oDateOne - oDateTwo < 0);_x000D_
alert(oDateOne - oDateTwo > 0);
_x000D_
_x000D_
_x000D_


In order to create dates from free text in Javascript you need to parse it into the Date() object.

You could use Date.parse() which takes free text tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.

Once you have a date as other people have pointed out you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).


To compare two date we can use date.js JavaScript library which can be found at : https://code.google.com/archive/p/datejs/downloads

and use the Date.compare( 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.


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

_x000D_
_x000D_
var oDateOne = new Date();_x000D_
var oDateTwo = new Date();_x000D_
_x000D_
alert(oDateOne - oDateTwo === 0);_x000D_
alert(oDateOne - oDateTwo < 0);_x000D_
alert(oDateOne - oDateTwo > 0);
_x000D_
_x000D_
_x000D_


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:

  • dates.compare(a,b)

    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: http://stackoverflow.com/questions/497790
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,d.date) :
            NaN
        );
    },
    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) :
            NaN
        );
    },
    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 :
            NaN
        );
    }
}

The simple way is,

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

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

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


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;
}

var date = new Date(); // will give you todays date.

// following calls, will let you set new dates.
setDate()   
setFullYear()   
setHours()  
setMilliseconds()   
setMinutes()    
setMonth()  
setSeconds()    
setTime()

var yesterday = new Date();
yesterday.setDate(...date info here);

if(date>yesterday)  // will compare dates

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));

     if(tform.START_DATE.value!=""){
         var estStartDate = tform.START_DATE.value;
         //format for Oracle
         tform.START_DATE.value = estStartDate + " 00:00:00";
     }

     if(tform.END_DATE.value!=""){
         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.


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);

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.


SHORT ANSWER

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

Explanation

jsFiddle

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 <=)

Then

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

Usage

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

DEMO

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


If following is your date format, you can use this code:

var first = '2012-11-21';
var second = '2012-11-03';
if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
   //...
}

It will check whether 20121121 number is bigger than 20121103 or not.


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;
                                            return;
                                        }
                    }
}
console.log("cannot select past pickup date");
isPastPickupDateSelected = true;

var date = new Date(); // will give you todays date.

// following calls, will let you set new dates.
setDate()   
setFullYear()   
setHours()  
setMilliseconds()   
setMinutes()    
setMonth()  
setSeconds()    
setTime()

var yesterday = new Date();
yesterday.setDate(...date info here);

if(date>yesterday)  // will compare dates

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


        from_date ='10-07-2012';
        to_date = '05-05-2012';
        var fromdate = from_date.split('-');
        from_date = new Date();
        from_date.setFullYear(fromdate[2],fromdate[1]-1,fromdate[0]);
        var todate = to_date.split('-');
        to_date = new Date();
        to_date.setFullYear(todate[2],todate[1]-1,todate[0]);
        if (from_date > to_date ) 
        {
            alert("Invalid Date Range!\nStart Date cannot be after End Date!")

            return false;
        }

Use this code to compare the date using javascript.

Thanks D.Jeeva


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;
}

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.


var date = new Date(); // will give you todays date.

// following calls, will let you set new dates.
setDate()   
setFullYear()   
setHours()  
setMilliseconds()   
setMinutes()    
setMonth()  
setSeconds()    
setTime()

var yesterday = new Date();
yesterday.setDate(...date info here);

if(date>yesterday)  // will compare dates

In order to create dates from free text in Javascript you need to parse it into the Date() object.

You could use Date.parse() which takes free text tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.

Once you have a date as other people have pointed out you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).


Via Moment.js

Jsfiddle: http://jsfiddle.net/guhokemk/1/

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


Say you got the date objects A and B, get their EPOC time value, then subtract to get the difference in milliseconds.

var diff = +A - +B;

That's all.


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.


The simple way is,

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

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

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:

  • dates.compare(a,b)

    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: http://stackoverflow.com/questions/497790
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,d.date) :
            NaN
        );
    },
    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) :
            NaN
        );
    },
    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 :
            NaN
        );
    }
}

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");
  }
 else
  {
    alert("Second Date  is greater than First Date");
  }

And also check this link http://www.w3schools.com/js/js_obj_date.asp


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>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true

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;
                }
            }
        }
    }
}

Performance

Today 2020.02.27 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6

Conclusions

  • solutions d1==d2 (D) and d1===d2 (E) are fastest for all browsers
  • solution getTime (A) is faster than valueOf (B) (both are medium fast)
  • solutions F,L,N are slowest for all browsers

enter image description here

Details

In below snippet solutions used in performance tests are presented. You can perform test in you machine HERE

_x000D_
_x000D_
function A(d1,d2) {_x000D_
 return d1.getTime() == d2.getTime();_x000D_
}_x000D_
_x000D_
function B(d1,d2) {_x000D_
 return d1.valueOf() == d2.valueOf();_x000D_
}_x000D_
_x000D_
function C(d1,d2) {_x000D_
 return Number(d1)   == Number(d2);_x000D_
}_x000D_
_x000D_
function D(d1,d2) {_x000D_
 return d1 == d2;_x000D_
}_x000D_
_x000D_
function E(d1,d2) {_x000D_
 return d1 === d2;_x000D_
}_x000D_
_x000D_
function F(d1,d2) {_x000D_
 return (!(d1>d2 || d2>d1));_x000D_
}_x000D_
_x000D_
function G(d1,d2) {_x000D_
 return d1*1 == d2*1;_x000D_
}_x000D_
_x000D_
function H(d1,d2) {_x000D_
 return +d1 == +d2;_x000D_
}_x000D_
_x000D_
function I(d1,d2) {_x000D_
 return !(+d1 - +d2);_x000D_
}_x000D_
_x000D_
function J(d1,d2) {_x000D_
 return !(d1 - d2);_x000D_
}_x000D_
_x000D_
function K(d1,d2) {_x000D_
 return d1 - d2 == 0;_x000D_
}_x000D_
_x000D_
function L(d1,d2) {_x000D_
 return !((d1>d2)-(d1<d2));_x000D_
}_x000D_
_x000D_
function M(d1,d2) {_x000D_
  return d1.getFullYear() === d2.getFullYear()_x000D_
    && d1.getDate() === d2.getDate()_x000D_
    && d1.getMonth() === d2.getMonth();_x000D_
}_x000D_
_x000D_
function N(d1,d2) {_x000D_
 return (isFinite(d1.valueOf()) && isFinite(d2.valueOf()) ? !((d1>d2)-(d1<d2)) : false );_x000D_
}_x000D_
_x000D_
_x000D_
// TEST_x000D_
_x000D_
let past= new Date('2002-12-24'); // past_x000D_
let now= new Date('2020-02-26');  // now_x000D_
_x000D_
console.log('Code  d1>d2  d1<d2  d1=d2')_x000D_
var log = (l,f) => console.log(`${l}     ${f(now,past)}  ${f(past,now)}  ${f(now,now)}`);_x000D_
_x000D_
log('A',A);_x000D_
log('B',B);_x000D_
log('C',C);_x000D_
log('D',D);_x000D_
log('E',E);_x000D_
log('G',G);_x000D_
log('H',H);_x000D_
log('I',I);_x000D_
log('J',J);_x000D_
log('K',K);_x000D_
log('L',L);_x000D_
log('M',M);_x000D_
log('N',N);
_x000D_
p {color: red}
_x000D_
<p>This snippet only presents tested solutions (it not perform tests itself)</p>
_x000D_
_x000D_
_x000D_

Results for chrome

enter image description here


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);

In order to create dates from free text in Javascript you need to parse it into the Date() object.

You could use Date.parse() which takes free text tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.

Once you have a date as other people have pointed out you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).


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>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true

Via Moment.js

Jsfiddle: http://jsfiddle.net/guhokemk/1/

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


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.


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 :)


Performance

Today 2020.02.27 I perform tests of chosen solutions on Chrome v80.0, Safari v13.0.5 and Firefox 73.0.1 on MacOs High Sierra v10.13.6

Conclusions

  • solutions d1==d2 (D) and d1===d2 (E) are fastest for all browsers
  • solution getTime (A) is faster than valueOf (B) (both are medium fast)
  • solutions F,L,N are slowest for all browsers

enter image description here

Details

In below snippet solutions used in performance tests are presented. You can perform test in you machine HERE

_x000D_
_x000D_
function A(d1,d2) {_x000D_
 return d1.getTime() == d2.getTime();_x000D_
}_x000D_
_x000D_
function B(d1,d2) {_x000D_
 return d1.valueOf() == d2.valueOf();_x000D_
}_x000D_
_x000D_
function C(d1,d2) {_x000D_
 return Number(d1)   == Number(d2);_x000D_
}_x000D_
_x000D_
function D(d1,d2) {_x000D_
 return d1 == d2;_x000D_
}_x000D_
_x000D_
function E(d1,d2) {_x000D_
 return d1 === d2;_x000D_
}_x000D_
_x000D_
function F(d1,d2) {_x000D_
 return (!(d1>d2 || d2>d1));_x000D_
}_x000D_
_x000D_
function G(d1,d2) {_x000D_
 return d1*1 == d2*1;_x000D_
}_x000D_
_x000D_
function H(d1,d2) {_x000D_
 return +d1 == +d2;_x000D_
}_x000D_
_x000D_
function I(d1,d2) {_x000D_
 return !(+d1 - +d2);_x000D_
}_x000D_
_x000D_
function J(d1,d2) {_x000D_
 return !(d1 - d2);_x000D_
}_x000D_
_x000D_
function K(d1,d2) {_x000D_
 return d1 - d2 == 0;_x000D_
}_x000D_
_x000D_
function L(d1,d2) {_x000D_
 return !((d1>d2)-(d1<d2));_x000D_
}_x000D_
_x000D_
function M(d1,d2) {_x000D_
  return d1.getFullYear() === d2.getFullYear()_x000D_
    && d1.getDate() === d2.getDate()_x000D_
    && d1.getMonth() === d2.getMonth();_x000D_
}_x000D_
_x000D_
function N(d1,d2) {_x000D_
 return (isFinite(d1.valueOf()) && isFinite(d2.valueOf()) ? !((d1>d2)-(d1<d2)) : false );_x000D_
}_x000D_
_x000D_
_x000D_
// TEST_x000D_
_x000D_
let past= new Date('2002-12-24'); // past_x000D_
let now= new Date('2020-02-26');  // now_x000D_
_x000D_
console.log('Code  d1>d2  d1<d2  d1=d2')_x000D_
var log = (l,f) => console.log(`${l}     ${f(now,past)}  ${f(past,now)}  ${f(now,now)}`);_x000D_
_x000D_
log('A',A);_x000D_
log('B',B);_x000D_
log('C',C);_x000D_
log('D',D);_x000D_
log('E',E);_x000D_
log('G',G);_x000D_
log('H',H);_x000D_
log('I',I);_x000D_
log('J',J);_x000D_
log('K',K);_x000D_
log('L',L);_x000D_
log('M',M);_x000D_
log('N',N);
_x000D_
p {color: red}
_x000D_
<p>This snippet only presents tested solutions (it not perform tests itself)</p>
_x000D_
_x000D_
_x000D_

Results for chrome

enter image description here


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");
}

else{
    alert("both date are same");
}

Compare day only (ignoring time component):

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

Usage:

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

I no longer recommend modifying the prototype of built-in objects. Try this instead:

_x000D_
_x000D_
function isSameDay(d1, d2) {
  return d1.getFullYear() === d2.getFullYear() &&
    d1.getDate() === d2.getDate() &&
    d1.getMonth() === d2.getMonth();
}


console.log(isSameDay(new Date('Jan 15 2021 02:39:53 GMT-0800'), new Date('Jan 15 2021 23:39:53 GMT-0800')));
console.log(isSameDay(new Date('Jan 15 2021 10:39:53 GMT-0800'), new Date('Jan 16 2021 10:39:53 GMT-0800')));
_x000D_
_x000D_
_x000D_

N.B. the year/month/day will be returned for your timezone; I recommend using a timezone-aware library if you want to check if two dates are on the same day in a different timezone.

e.g.

> (new Date('Jan 15 2021 01:39:53 Z')).getDate()  // Jan 15 in UTC
14  // Returns "14" because I'm in GMT-08

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.


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.


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:

  • dates.compare(a,b)

    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: http://stackoverflow.com/questions/497790
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,d.date) :
            NaN
        );
    },
    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) :
            NaN
        );
    },
    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 :
            NaN
        );
    }
}

An Improved version of the code posted by "some"

/* Compare the current date against another date.
 *
 * @param b  {Date} the other date
 * @returns   -1 : if this < b
 *             0 : if this === b
 *             1 : if this > b
 *            NaN : if a or b is an illegal date
*/ 
Date.prototype.compare = function(b) {
  if (b.constructor !== Date) {
    throw "invalid_date";
  }

 return (isFinite(this.valueOf()) && isFinite(b.valueOf()) ? 
          (this>b)-(this<b) : NaN 
        );
};

usage:

  var a = new Date(2011, 1-1, 1);
  var b = new Date(2011, 1-1, 1);
  var c = new Date(2011, 1-1, 31);
  var d = new Date(2011, 1-1, 31);

  assertEquals( 0, a.compare(b));
  assertEquals( 0, b.compare(a));
  assertEquals(-1, a.compare(c));
  assertEquals( 1, c.compare(a));

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

<a href="https://plnkr.co/edit/9N8ZcC?p=preview"> Live Demo</a>

If you are using **REACT OR REACT NATIVE**, use this and it will work (Working like charm)

If the two dates are the same, it will return TRUE otherwise FALSE

const compareDate = (dateVal1, dateVal2) => {
        if (dateVal1.valueOf() === dateVal2.valueOf()){
            return true;
        }
        else { return false;}
    }

In order to create dates from free text in Javascript you need to parse it into the Date() object.

You could use Date.parse() which takes free text tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.

Once you have a date as other people have pointed out you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).


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.


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;
                }
            }
        }
    }
}

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.


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:

  • dates.compare(a,b)

    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: http://stackoverflow.com/questions/497790
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,d.date) :
            NaN
        );
    },
    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) :
            NaN
        );
    },
    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 :
            NaN
        );
    }
}

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 :)


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;
}

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,)
            }
        </script>

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

    <script type="text/javascript">

              $(document).ready(function(){
              //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 {}
}
 });
    </script>

For Sure this code will help you.


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");
}

else{
    alert("both date are same");
}

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

<a href="https://plnkr.co/edit/9N8ZcC?p=preview"> Live Demo</a>

Say you got the date objects A and B, get their EPOC time value, then subtract to get the difference in milliseconds.

var diff = +A - +B;

That's all.


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));

     if(tform.START_DATE.value!=""){
         var estStartDate = tform.START_DATE.value;
         //format for Oracle
         tform.START_DATE.value = estStartDate + " 00:00:00";
     }

     if(tform.END_DATE.value!=""){
         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.


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; 
} 
else 
{ 
   alert("Submitting ...");
   document.form1.submit(); 
} 

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;
}

BEWARE THE TIMEZONE

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()

var date = new Date(); // will give you todays date.

// following calls, will let you set new dates.
setDate()   
setFullYear()   
setHours()  
setMilliseconds()   
setMinutes()    
setMonth()  
setSeconds()    
setTime()

var yesterday = new Date();
yesterday.setDate(...date info here);

if(date>yesterday)  // will compare dates

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

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
}

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.


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");
  }
 else
  {
    alert("Second Date  is greater than First Date");
  }

And also check this link http://www.w3schools.com/js/js_obj_date.asp


Compare day only (ignoring time component):

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

Usage:

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

I no longer recommend modifying the prototype of built-in objects. Try this instead:

_x000D_
_x000D_
function isSameDay(d1, d2) {
  return d1.getFullYear() === d2.getFullYear() &&
    d1.getDate() === d2.getDate() &&
    d1.getMonth() === d2.getMonth();
}


console.log(isSameDay(new Date('Jan 15 2021 02:39:53 GMT-0800'), new Date('Jan 15 2021 23:39:53 GMT-0800')));
console.log(isSameDay(new Date('Jan 15 2021 10:39:53 GMT-0800'), new Date('Jan 16 2021 10:39:53 GMT-0800')));
_x000D_
_x000D_
_x000D_

N.B. the year/month/day will be returned for your timezone; I recommend using a timezone-aware library if you want to check if two dates are on the same day in a different timezone.

e.g.

> (new Date('Jan 15 2021 01:39:53 Z')).getDate()  // Jan 15 in UTC
14  // Returns "14" because I'm in GMT-08

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;
                                            return;
                                        }
                    }
}
console.log("cannot select past pickup date");
isPastPickupDateSelected = true;

An Improved version of the code posted by "some"

/* Compare the current date against another date.
 *
 * @param b  {Date} the other date
 * @returns   -1 : if this < b
 *             0 : if this === b
 *             1 : if this > b
 *            NaN : if a or b is an illegal date
*/ 
Date.prototype.compare = function(b) {
  if (b.constructor !== Date) {
    throw "invalid_date";
  }

 return (isFinite(this.valueOf()) && isFinite(b.valueOf()) ? 
          (this>b)-(this<b) : NaN 
        );
};

usage:

  var a = new Date(2011, 1-1, 1);
  var b = new Date(2011, 1-1, 1);
  var c = new Date(2011, 1-1, 31);
  var d = new Date(2011, 1-1, 31);

  assertEquals( 0, a.compare(b));
  assertEquals( 0, b.compare(a));
  assertEquals(-1, a.compare(c));
  assertEquals( 1, c.compare(a));

If following is your date format, you can use this code:

var first = '2012-11-21';
var second = '2012-11-03';
if(parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
   //...
}

It will check whether 20121121 number is bigger than 20121103 or not.


BEWARE THE TIMEZONE

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()

SHORT ANSWER

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

Explanation

jsFiddle

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 <=)

Then

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

Usage

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

DEMO

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


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,)
            }
        </script>

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

    <script type="text/javascript">

              $(document).ready(function(){
              //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 {}
}
 });
    </script>

For Sure this code will help you.


        from_date ='10-07-2012';
        to_date = '05-05-2012';
        var fromdate = from_date.split('-');
        from_date = new Date();
        from_date.setFullYear(fromdate[2],fromdate[1]-1,fromdate[0]);
        var todate = to_date.split('-');
        to_date = new Date();
        to_date.setFullYear(todate[2],todate[1]-1,todate[0]);
        if (from_date > to_date ) 
        {
            alert("Invalid Date Range!\nStart Date cannot be after End Date!")

            return false;
        }

Use this code to compare the date using javascript.

Thanks D.Jeeva


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
}

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>t2-t1
2672
js>t3 = new Date('2009 Jan 1')
Thu Jan 01 2009 00:00:00 GMT-0500 (Eastern Standard Time)
js>t1-t3
2470768442
js>t1>t3
true

If you are using **REACT OR REACT NATIVE**, use this and it will work (Working like charm)

If the two dates are the same, it will return TRUE otherwise FALSE

const compareDate = (dateVal1, dateVal2) => {
        if (dateVal1.valueOf() === dateVal2.valueOf()){
            return true;
        }
        else { return false;}
    }

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

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; 
} 
else 
{ 
   alert("Submitting ...");
   document.form1.submit(); 
} 

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to compare

Checking for duplicate strings in JavaScript array How to compare two files in Notepad++ v6.6.8 How to compare LocalDate instances Java 8 Comparing the contents of two files in Sublime Text comparing elements of the same array in java How to compare two dates along with time in java bash string compare to multiple correct values Query comparing dates in SQL How to compare two java objects Comparing two integer arrays in Java