xxxxxxxxxx
const isSameDate = date1.getFullYear() === date2.getFullYear() &&
date1.getMonth() === date2.getMonth() &&
date1.getDate() === date2.getDate();
// the above implies they are in the same timezone
// if there's a possibility they are in different timezones
// you must convert them first to UTC before comparing
xxxxxxxxxx
var date1 = new Date('December 25, 2017 01:30:00');
var date2 = new Date('June 18, 2016 02:30:00');
//best to use .getTime() to compare dates
if(date1.getTime() === date2.getTime()){
//same date
}
if(date1.getTime() > date2.getTime()){
//date 1 is newer
}
xxxxxxxxxx
function compareDatesWithoutTime(date1, date2) {
const strippedDate1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
const strippedDate2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
return strippedDate1.getTime() === strippedDate2.getTime();
}
// Example usage
const date1 = new Date('2022-01-01T10:00:00');
const date2 = new Date('2022-01-01T15:30:00');
const result = compareDatesWithoutTime(date1, date2);
console.log(result); // Output: true
xxxxxxxxxx
// We initialize the Date() object with the current date and time
const date1 = new Date();
// We initialize a past date
const date2 = new Date('2018-04-07 12:30:00');
// Let's see if the first date is equal, more recent or less recent than the second date
if (date1.getTime() === date2.getTime()) {
console.log('The dates are equal');
}
else if (date1.getTime() > date2.getTime()) {
console.log(date1.toString() + ' is more recent than ' + date2.toString());
}
else {
console.log(date1.toString() + ' is less recent than ' + date2.toString());
}
xxxxxxxxxx
let date1 = new Date("2024-01-29T03:34:48.000Z"); // Tue Jan 29 2024 03:34:48 GMT+0000
let date2 = new Date("2024-01-29T15:00:00.000Z"); // Tue Jan 29 2024 15:00:00 GMT+0000
let date1String = date1.toDateString(); // "Tue Jan 29 2024"
let date2String = date2.toDateString(); // "Tue Jan 29 2024"
console.log(date1String === date2String); // Output: true
console.log(date1String < date2String); // Output: false
console.log(date1String > date2String); // Output: false
xxxxxxxxxx
var isLarger = new Date("2-11-2012 13:40:00") > new Date("01-11-2012 10:40:00");
xxxxxxxxxx
let myDate = new Date("January 13, 2021 12:00:00");
let yourDate = new Date("January 13, 2021 15:00:00");
if (myDate < yourDate) {
console.log("myDate is less than yourDate"); // will be printed
}
if (myDate > yourDate) {
console.log("myDate is greater than yourDate");
}
xxxxxxxxxx
let d1 = new Date();
let d2 = new Date();
// can use >, <, <=, <=
d1 > d2
d1 >= d2
// == won't work so can use this:
(d1 >= d2) && (d2 >= d1)
xxxxxxxxxx
a = new Date(1995,11,17);
b = new Date(1995,11,17);
a.getTime() === b.getTime() // prints true