簡體   English   中英

遍歷日期對象數組並比較哪個是最新的和最早的

[英]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。
  • 我只是使用了es6的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)));

  1. 獲取每個字符串日期,將其轉換為日期對象,然后將它們解析為時間戳數字
    .map(d => Date.parse(new Date(d)))
  2. 對時間戳數字數組進行排序
    .sort((a, b) => a - b)
  3. 將數字轉換為日期字符串
    .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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM