![](/img/trans.png)
[英]how to get the dates in the last 24 hours from an array of dates in javascript
[英]how to get the most recent dates from array of dates in javascript?
在這里,我從 API 收到這樣的日期數組,
let dates = ["22/1/2022","22/7/2022","9/10/2018"]
從這些日期開始,我需要獲取最近的日期,即22/07/2022
。
我從一個站點獲得了以下示例,此代碼僅在日期與YYYY/MM/DD
的格式匹配時才能正常工作。
代碼
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"]));
我們可以使用一些包,比如date-fns
fns 或momentjs
。 盡管 JS 本身可以實現日期格式(或),但要獲得所需的結果?
請讓我知道您的解決方案。
使用 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)
您可以使用純 Javascript 作為邏輯
getTime()
)找到最大值 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)))
按降序排序並返回第一個元素將完成工作。
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.