简体   繁体   English

如何使用 javascript 从 json 获取日期格式的最近日期值?

[英]How to get a recent date value in date format from json with javascript?

I have 2 questions based on the example below.根据下面的示例,我有 2 个问题。

1- How can I get the closest 'jsonData.te' value to today? 1-我怎样才能得到最接近今天的 'jsonData.te' 值?

2- How can I do the for loop in reverse without breaking this structure? 2-如何在不破坏此结构的情况下反向执行 for 循环? (for example, it will look at key: 27 first, it will end when it finds the value of te there) (例如,它会先看 key: 27 ,当它在那里找到 te 的值时它会结束)

Thanks..谢谢..

 var demo = document.getElementsByName("test"); var today = moment().format('YYYY-MM-DD'); for (const dem of demo) { const jsonObject = dem.getAttribute("value"); const jsonData = JSON.parse(jsonObject); console.log(jsonData.te); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="hidden" name="test" value='{"key": 21, "sd": "2021-05-22", "te": "de1"}'> <input type="hidden" name="test" value='{"key": 22, "sd": "2021-05-21", "te": "de2"}'> <input type="hidden" name="test" value='{"key": 23, "sd": "2021-05-20", "te": "de3"}'> <input type="hidden" name="test" value='{"key": 24, "sd": "2021-05-23", "te": "de4"}'> <input type="hidden" name="test" value='{"key": 25, "sd": "2021-05-25", "te": "de5"}'> <input type="hidden" name="test" value='{"key": 26, "sd": "2021-05-24", "te": "de6"}'> <input type="hidden" name="test" value='{"key": 27, "sd": "2021-05-26", "te": "de7"}'>

This way you can get the result you want.这样你就可以得到你想要的结果。

function sortt(son) {
    input = document.getElementsByName("test");
    var today = new Date();
    var today_t = today.getTime();
    var arre = [];
    for (i = 0; i < input.length; i++) {
        value = input[i].value;
        ndate = JSON.parse(value).sd;
        te = JSON.parse(value).te;
        var d1 = new Date(ndate);
        var s1 = d1.getTime();
        difff = s1 - today_t;
        if (difff > 0) {
            arre.push({ difff: difff, tei: te });
        }
    }
    arre.sort(function (a, b) {
        return a.difff - b.difff;
    });
    return arre[0].tei;
}

var relist = sortt(0);
console.log(relist);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM