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

时间:2010-12-14 19:02:05

标签: javascript arrays date

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

更新:如果这是一个关联数组怎么办?如何返回最近日期的密钥?

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)。

1 个答案:

答案 0 :(得分:2)

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

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);