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.
- 21When it comes to DateTime and manipulation in JS, I look no further than momentjs :)Halceyon– Halceyon2013-09-23 13:35:38 +00:00Commented Sep 23, 2013 at 13:35
- 112no need to use momentjs to compare 2 dates. Just use pure javascript's Date object. Check main answer for more details.Lukas Liesis– Lukas Liesis2016-06-09 05:26:02 +00:00Commented Jun 9, 2016 at 5:26
- You can refer following answer : stackoverflow.com/questions/4812152/… Check getDateDifference and getDifferenceInDays if it can help.Vikash Rajpurohit– Vikash Rajpurohit2016-11-03 10:46:51 +00:00Commented Nov 3, 2016 at 10:46
- 10For those like me who may have come along later, moment.js is now in "maintenance mode," i.e. no longer being actively developed.Bob Brown– Bob Brown2021-05-02 15:03:50 +00:00Commented May 2, 2021 at 15:03
- 2For 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-datessandypockets– sandypockets2022-03-20 18:43:45 +00:00Commented Mar 20, 2022 at 18:43
48 Answers
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
1 Comment
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
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
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
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
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
birthday+X entire years is (you can add years to JS dates), and then comparing with >= with a new Date()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
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
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
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
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:date1is less thandate2.0: two dates are equal.1:date1is greater thandate2.
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
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
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
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
getMinutes, getSeconds, etc methods.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
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(); }