JavaScript: How to compare dates

For an explanation of how to get an ISO date-time string, see this previous article:

JavaScript: How to create a formatted date time string

Let’s say we have two ISO date-time strings that we pulled from a MySQL database and we want to programmatically compare them to see which date is newer. Let’s set them up as d1 an d2:

let d1 = '2018-04-02T19:23:15.964Z';
let d2 = '2016-09-14T19:23:15.964Z';


Since these came from the database as strings, in order to compare them we first need to convert them into JavaScript Date() objects. For example:

d1 = new Date(d1);
d2 = new Date(d2);


Now that both ISO date-time strings have been converted into Date objects we  can compare them directly with traditional greater than-less than operators. For example:

let newer = (d1 > d2);
console.log("d1 is newer?:", newer)

Which yields:

d1 is newer?: true