javascript数组找到最近的日期与当前日期+ dayscounter

时间:2014-10-07 15:03:16

标签: javascript jquery json date object

请知道我必须从下面的对象中找到最近的日期,最近的日期将与系统日期+ dayscounter进行比较。

请帮助它对我来说会很有帮助。这里是jsFiddle链接: http://jsfiddle.net/g7rsp4b2/1/

<div class="component" data-datejson='{"success":{"yrdateslist":["October 10,2014","October 18,2014","October 22,2014","October 09,2014","October 21,2014","October 22,2014"],"dayscounter":"8"}}' id="onCampusDate">

</div>

var allDates = $('.component').data('datejson'); 
var dates = allDates.success.yrdateslist;
var dayscounter = allDates.success.dayscounter;
var now = new Date();
var newDates = [];
for (var i = 0; i < dates.length; i++) {
    newDates.push(dates[i]);
}

alert(newDates);
alert(now);

1 个答案:

答案 0 :(得分:0)

如下:

var allDates = $('.component').data('datejson'); 
var dates = allDates.success.yrdateslist;
var dayscounter = allDates.success.dayscounter;
var now = new Date();

//Add the days counter to now
now.setDate(now.getDate() + dayscounter);

//This is the key -> Sort by the difference in time
dates.sort(function(a,b){
    var nowTime = now.getTime(),
        atime = Math.abs(atime - nowTime),
        btime = Math.abs(btime- nowTime);

    return Math.abs(atime - btime); 
});

然后,您的结束日期应为dates[0];

请参阅:http://jsfiddle.net/g8ezcoz7/