简体   繁体   English

如何从 javascript 中的日期数组中获取最新日期?

[英]how to get the most recent dates from array of dates in javascript?

Here I am receiving the array of dates like this from the API,在这里,我从 API 收到这样的日期数组,

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

From these dates, I need to get the most recent date ie 22/07/2022 .从这些日期开始,我需要获取最近的日期,即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 .我从一个站点获得了以下示例,此代码仅在日期与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 .我们可以使用一些包,比如date-fns fns 或momentjs to get the desired result despite the date format (or) with JS itself its achievable?尽管 JS 本身可以实现日期格式(或),但要获得所需的结果?

Please let me know your solution for this.请让我知道您的解决方案。

With date-fns you can do it like使用 date-fns 你可以这样做

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)

You can use pure Javascript for the logic您可以使用纯 Javascript 作为逻辑

  • Convert strings to dates将字符串转换为日期
  • Use timestamps (by getTime() ) to find max使用时间戳(通过getTime() )找到最大值
  • 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)))

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM