How to compare Date and Time in JavaScript - Step by Step

Comparing dates is a recurring feature in any application. Whether it's the same date, earlier or later than the other date. Fortunately, JavaScript already has built-in features to do that.

We can compare dates by initializing them as a Date object and using the getTime() method with comparison operators. Example: date1.getTime() === date2.getTime()

Continue reading for a detailed explanation.

Explaining how to compare dates

Many developers, when they need to do some date operation, they soon think about adding Moment.js or another similar library, often without knowing that JavaScript alone can very well handle this kind of operation.

The Date object in JavaScript is the ideal structure for working with dates. It has the getTime() method that returns the value of a specific date in milliseconds and can be universally used to work with dates, regardless of timezone or format.

The most complicated part is to find examples regarding the date format, especially for formats like dd/mm/yyyy. But we'll look into that soon.

The code example below is probably the reason why you came here:

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

It may even be optional to use getTime() in some cases, but if we compare two Date objects that are the same, the result will be false, e.g: (new Date == new Date). That's why I always recommend using getTime(), to compare values regardless of whether the objects are different.

We use ===, because this is the correct way to check if two values of the same type are equal. e.g. 1 === 1 (true), 1 === '1' (false).

Comparing times only

If you need to compare two times, checking for example if 2:00 pm is greater than 3:00 am, just initialize the Date object with the dates on the same day:

// Let's suppose the variables time1 and time2 come from an input
var time1 = '14:00';
var time2 = '03:00';

const date1 = new Date('2020-01-01 ' + time1);
const date2 = new Date('2020-01-01 ' + time2);

// Verify if the first time is equal, more recent or less recent than the second
if (date1.getTime() === date2.getTime()) {
	console.log('Both times are equal');
}
else if (date1.getTime() > date2.getTime()) {
	console.log(time1 + ' is more recent than ' + time2);
}
else {
	console.log(time1 + ' is less recent than ' + time2);
}

If you want to know the difference between hours, minutes, etc.. See Difference Between Dates in JavaScript.

For complete date comparison or dates without time, the logic is the same, just make sure that the Date object is initialized in the correct way. See below.

Converting your dates to the right format

If you don't yet have your dates in the right format to initialize a Date object, we need to work with the string so we can make the comparisons above.

Remember that there are at least 5 ways to initialize a Date object:

// The date and time now
new Date();

// The date from a timestamp (integer value in milliseconds since 01/01/1970)
new Date(1554661034091);

// The date initialized from a valid date string
new Date('April 04 2019 12:30:30');
new Date('2019-04-07 12:30:30');

// The date initialized from another date object
var outroDia = new Date('2019-04-07 12:30:30');
new Date(outroDia);

// The date initialized from the Date constructor: Date(year, month - 1, day, hour, minute, second, millisecond)
new Date(2019, 04, 07, 12, 30, 30);

If your date is in the format 15-04-2019 or 15/04/2019, or 15 April 2019, we will need to make a conversion:

// Let's say this is your date format
let date = '15/04/2019';

// We need to break the string to return each part
const dataSplit = date.split('/');

const day = dataSplit[0]; // 15
const month = dataSplit[1]; // 04
const year = dataSplit[2]; // 2019

// Now we can initialize the Date object. Note that the month starts in zero, so we do -1.
data = new Date(year, month - 1, day);

You can encapsulate the above script within a function and use it on the two dates you need to compare.

If you still need to convert the times, just do the split in space after the year and in the ":".

Now, if you need to convert a date of type 04 April 2019, here's an example:

let data = '15 April 2019';

// We need to create an object with all the months
const months = { "January": 1, "February": 2, "March": 3, "April": 4 }; // ...

// Let's break the space
const dataSplit = data.split(' ');

const day = dataSplit[0]; // 15
const month = months[dataSplit[1]]; // April -> 4
const year = dataSplit[2]; // 2019

// Now we can initialize the Date object. Note that month starts in zero, so we do month - 1.
data = new Date(year, month - 1, day);

Checking if a date is within 2 other dates

If you need to check if, for example, April 5th is within April 1st and April 30th, we can use the same logic of comparison:

// Initial date
const dateStart = new Date('2019-04-01');
// Final date
const dateEnd = new Date('2019-04-30');
// The date we need to compare
const dateIndex = new Date('2019-04-05');

if (dateStart.getTime() < dateIndex.getTime() && dateEnd.getTime() > dateIndex.getTime()) {
	console.log('The date is within the specified period');
}
else {
	console.log('The date is out of the specified period');
}

How to know the difference between two dates

If you want to know the difference between two dates returning days, months, years, etc.. I wrote another article on this subject: https://ricardometring.com/difference-between-dates-in-javascript.

Did you find this helpful?

Ricardo Metring

Ricardo Metring

Full stack web developer and co-founder at Criar.io.
I've worked for over 10 years with software development. I'm constantly curious and learning.

Linkedin     Github

Related articles