You’re comparing strings. That compares their characters, one by one from left-to-right, until it finds a difference, and then uses that difference as the result. Since "2"
is >
"0"
, that string is greater than the other.
You need to parse the dates and compare the result. Do not just use new Date(dateFormat)
or similar, those strings are not in a format that is handled by JavaScript’s Date
object. Do the parsing yourself (directly, or via a library). E.g.
var dateFormat = "01/05/2099";
var dateMissing = "25/11/2016";
var parts, dt1, dt2;
var parts = dateFormat.split("https://stackoverflow.com/");
var dt1 = new Date(+parts[2], +parts[1] - 1, +parts[0]);
parts = dateMissing.split("https://stackoverflow.com/");
var dt2 = new Date(+parts[2], +parts[1] - 1, +parts[0]);
if (dt1 > dt2) {
dateFormat = dateMissing;
}
console.log("dateFormat:", dateFormat);
console.log("dt1", dt1.toString());
console.log("dt2", dt2.toString());
solved Time if statement not working