Here I am receiving the array of dates like this from the API,
let dates = ["22/1/2022","22/7/2022","9/10/2018"]
From these dates, I need to get the most recent date i.e 22/07/2022.
I got the below example from a site, This code works correctly only if the date matches the format of YYYY/MM/DD.
CODE
function max_date(all_dates) {
var max_dt = all_dates[0],
max_dtObj = new Date(all_dates[0]);
all_dates.forEach(function (dt, index) {
if (new Date(dt) > max_dtObj) {
max_dt = dt;
max_dtObj = new Date(dt);
}
});
return max_dt;
}
console.log(max_date(["2015/02/01", "2022/02/02", "2023/01/03"]));
Can we use some packages like date-fns or momentjs . to get the desired result despite the date format (or) with JS itself its achievable?
Please let me know your solution for this.