我正在嘗試處理一些與日期密切相關的資料。如下面的片段所示,我試圖找到離今天最近的一天的索引。我正在使用date-fns實用程式庫來完成這項作業。雖然我嘗試記錄closestIndexfrom 它作業正常并在終端中獲得輸出,但是當我嘗試利用的值時,closestIndex我得到一個錯誤,說closestIndexis undefined。任何想法將不勝感激。
import * as dateFns from 'date-fns';
const today = new Date().getTime();
const dates = [
2022-04-10T14:07:12.276Z,
2022-04-10T14:07:06.967Z,
2022-04-10T14:07:04.663Z,
2022-04-10T14:07:03.040Z,
2022-04-10T14:07:01.420Z,
2022-04-10T14:06:59.869Z,
2022-04-10T14:06:53.223Z
]
const closestIndex = dateFns.closestTo(today, dates);
console.log(closestIndex); // => 0
console.log(dates[closestIndex]); // => undefined could not be used as index value
uj5u.com熱心網友回復:
您應該在陣列中使用真實的 Date 物件(而不是甚至沒有參考的 ISO-8601 值)并使用closeIndexTo而不是closeTo(這將回傳 Date 值本身而不是它在陣列中的索引)
const today = new Date().getTime();
const dates = [
new Date('2022-04-10T14:07:12.276Z'),
new Date('2022-04-10T14:07:06.967Z'),
new Date('2022-04-10T14:07:04.663Z'),
new Date('2022-04-10T14:07:03.040Z'),
new Date('2022-04-10T14:07:01.420Z'),
new Date('2022-04-10T14:06:59.869Z'),
new Date('2022-04-10T14:06:53.223Z')
]
const closestIndex = dateFns.closestIndexTo(today, dates);
console.log(closestIndex); // => 0
console.log(dates[closestIndex]); // => "2022-04-10T14:07:12.276Z"
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.30.1/date_fns.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/459839.html
標籤:javascript 日期 约会时间 日期-fns
