compare two dates javascript code example
Example 1: javascript difference between two dates
const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
console.log(getDifferenceInDays(date1, date2));
console.log(getDifferenceInHours(date1, date2));
console.log(getDifferenceInMinutes(date1, date2));
console.log(getDifferenceInSeconds(date1, date2));
function getDifferenceInDays(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60 * 60 * 24);
}
function getDifferenceInHours(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60 * 60);
}
function getDifferenceInMinutes(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / (1000 * 60);
}
function getDifferenceInSeconds(date1, date2) {
const diffInMs = Math.abs(date2 - date1);
return diffInMs / 1000;
}
Example 2: compare dates in js
var date1 = new Date('December 25, 2017 01:30:00');
var date2 = new Date('June 18, 2016 02:30:00');
if(date1.getTime() === date2.getTime()){
}
if(date1.getTime() > date2.getTime()){
}
Example 3: compare dates in javascript
var date1 = new Date('December 25, 2017 01:30:00');
var date2 = new Date('June 18, 2016 02:30:00');
if(date1.getTime() === date2.getTime()){
}
if(date1.getTime() > date2.getTime()){
}
Example 4: compare date javascript
start = startDate.getTime();
end = endDate.getTime();
current = date.getTime();
if (start <= current && current <= end) {
}
Example 5: date compare in js
var x = new Date('2013-05-23');
var y = new Date('2013-05-23');
x < y; => false
x > y; => false
x === y; => false, oops!
+x <= +y; => true
+x >= +y; => true
+x === +y; => true
Example 6: javascript compare dates
let d1 = new Date();
let d2 = new Date();
d1 > d2
d1 >= d2
(d1 >= d2) && (d2 >= d1)