2859

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.

7
  • 21
    When it comes to DateTime and manipulation in JS, I look no further than momentjs :) Commented Sep 23, 2013 at 13:35
  • 112
    no need to use momentjs to compare 2 dates. Just use pure javascript's Date object. Check main answer for more details. Commented Jun 9, 2016 at 5:26
  • You can refer following answer : stackoverflow.com/questions/4812152/… Check getDateDifference and getDifferenceInDays if it can help. Commented Nov 3, 2016 at 10:46
  • 10
    For those like me who may have come along later, moment.js is now in "maintenance mode," i.e. no longer being actively developed. Commented May 2, 2021 at 15:03
  • 2
    For those that have come along even later, moment.js is not only in maintenance mode, but it's a huge library (4.21mb!). If you only need simple functionality like comparing two dates, then you might try a tiny (20kb) lib I've been working on npmjs.com/package/easy-dates Commented Mar 20, 2022 at 18:43

48 Answers 48

1
2
1
 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

Sign up to request clarification or add additional context in comments.

1 Comment

I think this is a good answer because we have "dd/mm/yy" format and we have to do it to compare both dates. I don't know if it is the best answer but it is enough. Thank you for share.
1
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; } 

Comments

1

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.

Comments

1

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; 

Comments

1

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

Comments

1

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

2 Comments

If you post a new question asking "how to check in JS if date is at least X years ago", this would make a good answer. I suspect it can be simplified by calculating what birthday+X entire years is (you can add years to JS dates), and then comparing with >= with a new Date()
Sure. Of course there might be better answers. My answer was just to show the POINT. It might not be the best answer. It'd be great if you could simplify it!😁👍
1

Solution

To get the difference in days of two dates, allowing to ignore time:

const MS_PER_DAY = 24 * 60 * 60 * 1000; const compareDates = (a/*: Date*/, b/*: Date*/, ignoreTime = true)/*: number*/ => { if (ignoreTime) { a.setHours(0, 0, 0, 0); b.setHours(0, 0, 0, 0); } const diffInMs = a.getTime() - b.getTime(); return Math.round(diffInMs / MS_PER_DAY); }; 

Comments

0

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.

Comments

0
function compare_date(date1, date2){ const x = new Date(date1) const y = new Date(date2) function checkyear(x, y){ if(x.getFullYear()>y.getFullYear()){ return "Date1 > Date2" } else if(x.getFullYear()<y.getFullYear()){ return "Date2 > Date1" } else{ return checkmonth(x, y) } } function checkmonth(x, y){ if(x.getMonth()>y.getFullYear()){ return "Date1 > Date2" } else if(x.getMonth()<y.getMonth){ return "Date2 > Date1" } else { return checkDate(x, y) } } function checkDate(x, y){ if(x.getDate()>y.getFullYear()){ return "Date1 > Date2" } else if(x.getDate()<y.getDate()){ return "Date2 > Date1" } else { return checkhour(x,y) } } function checkhour(x, y){ if(x.getHours()>y.getHours()){ return "Date1 > Date2" } else if(x.getHours()<y.getHours()){ return "Date2 > Date1" } else { return checkhmin(x,y) } } function checkhmin(x,y){ if(x.getMinutes()>y.getMinutes()){ return "Date1 > Date2" } else if(x.getMinutes()<y.getMinutes()){ return "Date2 > Date1" } else { return "Date1 = Date2" } } return checkyear(x, y) 

Comments

0

sort way on JS

const date1 = '2022-01-01T00:00:00.000Z'; const date2 = '2022-02-01T00:00:00.000Z'; const diffDays = Math.ceil(Math.abs(new Date(date2).getTime() - new Date(date1).getTime()) / 86400000); console.log(diffDays); 

Comments

0
 var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]; var selectedDate= $('#hstdtContractTodate').val() ; //23-Feb-2023 var date1=new Date((selectedDate.split("-")[2]) +"/"+(months.indexOf(selectedDate.split("-")[1].toLowerCase()) + 1) +"/"+(selectedDate.split("-")[0])); // year/month/day var currentDate = new Date().toDateString(); var currdate = new Date((currentDate.split(" ")[3]) + "/" + (months.indexOf(currentDate.split(" ")[1].toLowerCase()) + 1) + "/" + (currentDate.split(" ")[2])); // year/month/day alert(currdate.getTime()===date1.getTime()) 

Comments

0

We know that subtracting two dates gives you the difference between two dates in milliseconds:

function compareTwoDates(d1, d2){ const date1 = new Date(d1); const date2 = new Date(d2); return date1 - date2; } 

Check the returned number from function if:

  • -1: date1 is less than date2.
  • 0 : two dates are equal.
  • 1 : date1 is greater than date2.

Example of use:

function compareTwoDates(d1, d2) { const date1 = new Date(d1); const date2 = new Date(d2); return date1 - date2; } let dateString1 = '2023-06-22'; let dateString2 = '2023-06-23'; let datesComparisonResult = compareTwoDates(dateString1, dateString2); if (datesComparisonResult > 0) { //1 console.log(`${dateString1} is greater than ${dateString2}`) } else if (datesComparisonResult < 0) { //-1 console.log(`${dateString1} is less than ${dateString2}`) } else { //0 console.log(`Both dates are equal`) }

Comments

0

In this code time is not considered.

let date = "put date here"; let dateNow =new Date(Date.now()).toLocaleDateString(); dateNow = new Date(dateNow); let dateVerified = new Date(date).toLocaleDateString(); dateVerified =new Date(dateVerified); console.log(dateNow); console.log(dateVerified ); console.log(dateNow-dateVerified ); //if 0 -> same date or 'today' 

Comments

-1

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> 

Comments

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

3 Comments

you answer looks like @Sanjeev Singh answer, can you explain what is the differnace ?
I didn't do copy and paste. Remember I said the code works for React and React Native App. I just created a functional component that will compare the two dates and return either true or false value.
Infact there is a big difference between@Sanjeev code and mine. Others are writting solutions for javascript, while I choosed to write for React.js and React Native.
-2

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

2 Comments

There's absolutely no reason to do string splitting on a date like that when you can just use the getMinutes, getSeconds, etc methods.
Why the hell do I keep losing reputation when this answer gets downvoted?
-7

using momentjs for dates manipulation.


For checking one date is same or after as another by using

isSameOrAfter() method

moment('2010-10-20').isSameOrAfter('2010-10-20') //true; 

For checking one date is after as another by using isAfter() method

moment('2020-01-20').isAfter('2020-01-21'); // false moment('2020-01-20').isAfter('2020-01-19'); // true 

For checking one date is before another by using isBefore() method.

moment('2020-01-20').isBefore('2020-01-21'); // true moment('2020-01-20').isBefore('2020-01-19'); // false 

For checking one date is same as another by using isSame() method

moment('2020-01-20').isSame('2020-01-21'); // false moment('2020-01-20').isSame('2020-01-20'); // true 

1 Comment

Shouldn't need additional JavaScript mods to accomplish this.
-8

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

1 Comment

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.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.