Reputation: 40425
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.
Upvotes: 2839
Views: 3518930
Reputation: 272316
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 dates because:
- If the operands have the same type, they are compared as follows:
- Object: return
true
only if both 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.
Upvotes: 219
Reputation: 859
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'
Upvotes: 0
Reputation: 9213
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`)
}
Upvotes: 0
Reputation: 355
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);
};
Upvotes: 1
Reputation: 91
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())
Upvotes: 0
Reputation: 7461
By far the easiest method is to subtract one date from the other and compare the result.
var oDateOne = new Date();
var oDateTwo = new Date();
console.log(oDateOne - oDateTwo === 0);
console.log(oDateOne - oDateTwo < 0);
console.log(oDateOne - oDateTwo > 0);
Upvotes: 109
Reputation: 43
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);
Upvotes: 0
Reputation: 89145
The Date object will do what you want - construct one for each date, then compare them using the >
, <
, <=
or >=
.
The ==
, !=
, ===
, and !==
operators require you to use date.getTime()
as in
var d1 = new Date();
var d2 = new Date(d1);
var same = d1.getTime() === d2.getTime();
var notSame = d1.getTime() !== d2.getTime();
to be clear just checking for equality directly with the date objects won't work
var d1 = new Date();
var d2 = new Date(d1);
console.log(d1 == d2); // prints false (wrong!)
console.log(d1 === d2); // prints false (wrong!)
console.log(d1 != d2); // prints true (wrong!)
console.log(d1 !== d2); // prints true (wrong!)
console.log(d1.getTime() === d2.getTime()); // prints true (correct)
I suggest you use drop-downs or some similar constrained form of date entry rather than text boxes, though, lest you find yourself in input validation hell.
For the curious, date.getTime()
documentation:
Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)
Upvotes: 3378
Reputation: 1326
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 and 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).
Upvotes: 7
Reputation: 435
One way to compare two dates is to use the dates.js
library.
The Date.compare(Date date1, Date date2)
method that returns a number which means the one of following result:
-1
= date1
is less than date2
.0
= values are equal.1
= date1
is greater than date2
.Upvotes: 9
Reputation: 1448
You can 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 the MDN article for the Date
class.
Upvotes: 19
Reputation: 476
If both of your dates come in the format "YYYY-MM-DD", you can skip the Date object and compare strings directly.
This works because of how the strings are compared in JS
let date1 = '2022-12-13';
let date2 = '2022-02-13';
console.log(`${date1} > ${date2}`, date1 > date2);
console.log(`${date1} < ${date2}`, date1 < date2);
console.log(`${date1} == ${date2}`, date1 == date2);
Upvotes: 2
Reputation: 369
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
Upvotes: -7
Reputation: 10280
Compare <
and >
just as usual, but anything involving ==
or ===
should use a +
prefix. Like so:
const x = new Date('2013-05-23');
const y = new Date('2013-05-23');
// less than, greater than is fine:
console.log('x < y', x < y); // false
console.log('x > y', x > y); // false
console.log('x <= y', x <= y); // true
console.log('x >= y', x >= y); // true
console.log('x === y', x === y); // false, oops!
// anything involving '==' or '===' should use the '+' prefix
// it will then compare the dates' millisecond values
console.log('+x === +y', +x === +y); // true
Upvotes: 567
Reputation: 1288
My simple answer for this question
checkDisabled(date) {
const today = new Date()
const newDate = new Date(date._d)
if (today.getTime() > newDate.getTime()) {
return true
}
return false
}
Upvotes: 2
Reputation: 581
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)
Upvotes: 0
Reputation: 189836
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
Upvotes: 44
Reputation: 283213
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:
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')));
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
Upvotes: 59
Reputation: 498
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;}
}
Upvotes: -1
Reputation: 92657
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
d1==d2
(D) and d1===d2
(E) are fastest for all browsersgetTime
(A) is faster than valueOf
(B) (both are medium fast)In below snippet solutions used in performance tests are presented. You can perform test in you machine HERE
function A(d1,d2) {
return d1.getTime() == d2.getTime();
}
function B(d1,d2) {
return d1.valueOf() == d2.valueOf();
}
function C(d1,d2) {
return Number(d1) == Number(d2);
}
function D(d1,d2) {
return d1 == d2;
}
function E(d1,d2) {
return d1 === d2;
}
function F(d1,d2) {
return (!(d1>d2 || d2>d1));
}
function G(d1,d2) {
return d1*1 == d2*1;
}
function H(d1,d2) {
return +d1 == +d2;
}
function I(d1,d2) {
return !(+d1 - +d2);
}
function J(d1,d2) {
return !(d1 - d2);
}
function K(d1,d2) {
return d1 - d2 == 0;
}
function L(d1,d2) {
return !((d1>d2)-(d1<d2));
}
function M(d1,d2) {
return d1.getFullYear() === d2.getFullYear()
&& d1.getDate() === d2.getDate()
&& d1.getMonth() === d2.getMonth();
}
function N(d1,d2) {
return (isFinite(d1.valueOf()) && isFinite(d2.valueOf()) ? !((d1>d2)-(d1<d2)) : false );
}
// TEST
let past= new Date('2002-12-24'); // past
let now= new Date('2020-02-26'); // now
console.log('Code d1>d2 d1<d2 d1=d2')
var log = (l,f) => console.log(`${l} ${f(now,past)} ${f(past,now)} ${f(now,now)}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
p {color: red}
<p>This snippet only presents tested solutions (it not perform tests itself)</p>
Results for chrome
Upvotes: 6
Reputation: 1781
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;
}
}
}
}
}
Upvotes: 1
Reputation: 419
The simple way is,
var first = '2012-11-21';
var second = '2012-11-03';
if (new Date(first) > new Date(second) {
.....
}
Upvotes: 24
Reputation: 104870
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
Upvotes: 87
Reputation: 13868
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
Upvotes: 14
Reputation: 2036
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;
}
Upvotes: 6
Reputation: 29020
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()
Upvotes: 13
Reputation: 243
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.
Upvotes: 0
Reputation: 17102
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
}
Upvotes: 9
Reputation: 49
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>
Upvotes: -1
Reputation: 4066
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.
Upvotes: 27