If you have the consistent string format of "YYYY-MM"
, e.g. "2020-10"
, "2021-01"
, you don't even have to convert them to date for accurate comparison, just compare the string value directly if you just want to know which month is the later month.
Try this:
var d1 = "2020-12";
var d2 = "2021-01";
var greaterMth = d2 > d1 ? d2 : d1;
alert("Greater month is: " + greaterMth);
But for your case, that will be:
var d1 = new Date("Jan-2016");
var d2 = new Date("Jan-2015");
greaterMth = d2 > d1 ? "Jan-2015" : "Jan-2016";
alert("Greater month is: " + greaterMth);
You don't even have to bother about the 1st of the month generated by the new Date()
.