0

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.

1

3 Answers 3

1

With date-fns you can do it like

import { max, parse } from "date-fns"

const dates = ["22/1/2022","22/7/2022","9/10/2018"];

console.log(max(dates.map((d) => parse(d, "d/M/yyyy", new Date()))))
// returns Fri Jul 22 2022 00:00:00 GMT+0200 (Central European Summer Time)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use pure Javascript for the logic

  • Convert strings to dates
  • Use timestamps (by getTime()) to find max
  • Convert that max timestamp back to date or string

const dates = ["22/1/2022", "22/7/2022", "9/10/2018"]

const convertStringToDate = (dateString) => {
  const [day, month, year] = dateString.split("/");

  return new Date(year, month - 1, day);
}

function format(inputDate) {
  let date, month, year;

  date = inputDate.getDate();
  month = inputDate.getMonth() + 1;
  year = inputDate.getFullYear();

  return `${date}/${month}/${year}`;
}

const timestamps = dates.map(date => convertStringToDate(date).getTime())

const max = Math.max(...timestamps)

console.log(format(new Date(max)))

Comments

1

Sorting in descending order and returning the first element will do the work.

let dates = ['22/1/2022', '22/7/2022', '9/10/2018'];

const latestDate = (dates) => {
  dates.sort((a, b) => {
    const date1 = new Date(a.split('/').reverse().join('-'));
    const date2 = new Date(b.split('/').reverse().join('-'));

    return date2 - date1;
  });

  // First el will be latest date
  return dates[0];
};

console.log(latestDate(dates));
// Output: 22/7/2022

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.