簡體   English   中英

在日期數組中如何從給定日期(javascript)中找到最接近的前一個日期?

[英]In an array of dates how to find closest previous date from a given date (javascript)?

我有一個日期相隔三天的數組,即 2 月 10 日、2 月 13 日、2 月 16 日等。

var givenDate = new Date();

givenDate.setDate(12);

在上面的數組中,我想從 givenDate 中找到最接近的前一個日期 - 所以答案應該是 2 月 10 日(因為它是最接近 2 月 12 日的前一個日期)。

我在其中一個論壇中找到了這個以獲得最近的日期:


var bestDate = dates.length; // dates is the name of my array

var bestDiff = -(new Date(0,0,0)).valueOf();

var currDiff = 0;

var i;

for(i = 0; i < dates.length; ++i){

   currDiff = Math.abs(between[i] - testDate);

   if(currDiff < bestDiff){

       bestDate = i;

       bestDiff = currDiff;

   }   
}

// the best date will be days[bestDate] 

document.write(dates[bestDate]);

問題在於它給出了最近的日期,這可能是下一個日期而不是前一個日期。 就像 2 月 12 日一樣,它會給出 2 月 13 日而不是 2 月 10 日。

謝謝你。

1)以相反的順序排序,以便(從樣本日期開始排在第 16 位,倒數第 10 位)
2) 在上面排序的數組上使用find方法來獲取可用日期中最接近的上一個日期。

更新:謝謝@RobG,很高興知道。
@Masoom,不要使用find ,而是使用findIndex來獲取日期索引。 然后就可以輕松下一個了。 附注。 您需要確保邊緣情況和訪問越界索引。 (當未找到或​​上一個日期為0索引時,findIndex 將返回 -1,然后將沒有任何第二天)

 const dates = [ new Date(2020, 1, 10), new Date(2020, 1, 13), new Date(2020, 1, 16) ]; const my_date = new Date(2020, 1, 12); const prev_date_index = dates .sort((a, b) => (b - a)) .findIndex(date => date - my_date <= 0); const prev_date = dates[prev_date_index]; const next_date = dates[prev_date_index - 1]; console.log(prev_date.toDateString()); console.log(next_date.toDateString());

您選擇的代碼不適合您陳述的原因,您的解決方案可以簡單得多。 您想找到日期之前的最后一個日期,因此只需從測試日期中減去每個日期,當結果為 0 或負數時,前一個日期就是您想要的日期。

您還應該處理越界值,例如在開始之前或結束之后。 我已經猜到你在這些情況下想要什么,你需要考慮需要做什么並調整邏輯以適應。

例如

 // Get last element of arr that is before d function getPrevious(d, arr) { let i = 0; while (d - arr[i] > 0 && i < arr.length - 1) { i++; } return i == 0? void 0 : arr[--i] ; } // Sample data let dates = [ new Date(2020, 1, 10), // 2020-02-10 new Date(2020, 1, 13), // 2020-02-13 new Date(2020, 1, 16), // 2020-02-16 new Date(2020, 1, 19) // 2020-02-19 ]; // Test dates [new Date(2020, 1, 8), // 2020-02-08 -> before start -> undefined new Date(2020, 1, 12), // 2020-02-12 -> within range -> 10 Feb new Date(2020, 2, 12) // 2020-03-12 -> after end -> last date ].forEach(d => { let result = getPrevious(d, dates); console.log(`${d.toDateString()} -> ${result? result.toDateString() : result}`) });

  • 種類
  • getIndex 並檢索值

 var datesArray = [new Date("02-10-2020"), new Date("02-13-2020"), new Date("02-16-2020")]; var newDateToInsert = new Date("02-12-2020"); datesArray.push(newDateToInsert); datesArray.sort((a, b) => a - b); var index = (datesArray.indexOf(newDateToInsert) - 1) >= 0 ? datesArray.indexOf(newDateToInsert) - 1 : datesArray.indexOf(newDateToInsert); console.log(datesArray[index]);

- - 編輯 - -
你也可以在新數組中克隆它,就像下面給出的那樣不改變原始數組 -

var datesArray = [new Date("02-10-2020"), new Date("02-13-2020"), new Date("02-16-2020")];

var newDateToInsert = new Date("02-12-2020");
var tempArray = [].concat(datesArray);
tempArray.push(newDateToInsert);

tempArray.sort((a, b) => a - b);
var index = (tempArray.indexOf(newDateToInsert) - 1) >= 0 ? tempArray.indexOf(newDateToInsert) - 1 : tempArray.indexOf(newDateToInsert);
console.log(datesArray[index]);

你好,

解決方案

let dates = // --> your dates array
let givenDate = new Date();
let givenDateInMS = givenDate.getTime();

let prevTimeDiff = Infinity;
let closestDate = null;
dates.forEach((date, index) => {
 let timeInMS = date.getTime();
 let timeDiff = givenDateInMS - timeInMS;
 if((timeDiff > 0) && (timeDiff < prevTimeDiff)) {
    prevTimeDiff = timeDiff;
    closestDate = date;
 }
})

if(closestDate != null){
 // here you have it
 console.log(closestDate)
}else{
 //there is no prev closest date (all dates might be greater than given date)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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