gpt4 book ai didi

javascript - 给定日期字符串的关联数组,找到下一个最接近的日期

转载 作者:行者123 更新时间:2023-11-30 18:49:18 25 4
gpt4 key购买 nike

给定日期字符串的关联数组,我如何找到今天或之后的下一个最近日期?

更新:如果这是一个关联数组呢?如何返回最近日期的 key ?

var matchdays = {};

7386: "09/14/2010"
7387: "09/29/2010"
7388: "10/20/2010"
7389: "11/02/2010"
7390: "11/24/2010"
7391: "12/07/2010"
7392: "12/18/2010"

例如,我希望它返回 7392,因为 12/18 在今天 (12/14) 或之后。

最佳答案

对您的数组进行排序,然后搜索直到找到晚于今天的日期。您还可以根据数组的大小和性能要求进行二进制搜索或其他奇特的操作。

var today = new Date();

dateList.sort();

var nextLater = null;

for (var i = 0; i < dateList.length; i++) {
if (dateList[i] > today) {
nextLater = dateList[i];
break;
}
}

更新

关联数组有点棘手。您可以按日期对键进行排序,然后执行与上述相同的操作,或者您可以简单地一次遍历一个键,跟踪从今天开始的最小正偏移量。前者是这样的:

// Function to get the keys
function keys(obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}
return keys;
}

// Get the keys, then sort the keys by there associated date
var keys = keys(matchdays).sort(function(a, b) {
var d1 = new Date(matchdays[a]);
var d2 = new Date(matchdays[b]);

return d1 - d2;
});

// Iterate through the keys, finding the key associated with the next date after today
var today = new Date();
var nextLater = null;

for (var i = 0; i < keys.length; i++) {
var date = new Date(matchdays[keys[i]]);

if (date > today) {
nextLater = keys[i];
break;
}
}

alert(nextLater);

排序增加了一些冗余,因为蛮力搜索将是 O(n),而最佳情况排序也将是 O(n)。所以对于暴力搜索,只需:

// Function to get the keys
function keys(obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}
return keys;
}

// Get the keys
var keys = keys(matchdays);

// Iterate through the keys, finding the key associated with the next date after today
var today = new Date();
var nextLater = null;
var min;

for (var i = 0; i < keys.length; i++) {
var date = new Date(matchdays[keys[i]]);

var diff = date - today;

if (diff > 0 && (min == undefined || diff < min ) {
min = diff
nextLater = keys[i];
}
}

alert(nextLater);

关于javascript - 给定日期字符串的关联数组,找到下一个最接近的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4443070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com