![](/img/trans.png)
[英]Sort an array of objects by hour minutes in ascending order from earliest to latest
[英]Loop through array of Date Objects and compare which one is latest and earliest
如果我有這個結構:
const datesList = [2022-07-15T19:41:12.620Z, 2022-07-20T11:21:52.596Z, 2022-07-13T11:21:50.596Z]
我如何遍歷它並找出哪個是較晚和較早的日期?
我試過使用 forEach 循環,但它不起作用..
您可以使用 getTime() 進行比較,它以毫秒為單位獲取自 1970 年以來的時間
var dateList = [new Date(Date.parse("2022-07-15T19:41:12.620Z")), new Date(), new Date(+5), new Date(1236876666273)] console.log(dateList.sort(function(a, b) { if (a.getTime() < b.getTime()) { return -1 } if (a.getTime() > b.getTime()) { return 1 } return 0 }))
Date.parse()
返回自 1970 年 1 月 1 日 00:00:00 UTC 以來輸入的字符串的毫秒數,用於valie date。dort
功能。 const datesList = ["2022-07-15T19:41:12.620Z", "2022-07-20T11:21:52.596Z", "2022-07-13T11:21:50.596Z"]; console.log(datesList.sort((a, b) => Date.parse(a) - Date.parse(b)));
.map(d => Date.parse(new Date(d)))
.sort((a, b) => a - b)
.map(t => new Date(t));
const dates = ['2022-07-15T19:41:12.620Z', '2022-07-20T11:21:52.596Z', '2022-07-13T11:21:50.596Z']; let output = dates .map(d => Date.parse(new Date(d))) .sort((a, b) => a - b) .map(t => new Date(t)); console.log(output);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.