【问题标题】:Given an associative array of Date strings, find the next closest date给定一个日期字符串的关联数组,找到下一个最接近的日期
【发布时间】:2010-12-14 19:02:04
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript arrays date


    【解决方案1】:

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

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

    【讨论】:

    • 抱歉 - 我更新了我的问题以反映我有兴趣使用 associative 数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多