比较日期并删除它是否比今天更早

时间:2014-05-16 02:12:42

标签: javascript jquery arrays

如果日期早于"我将如何删除日期。"如何附加所有项目而不仅仅是日期?我希望我至少走在正确的轨道上。

    var future =  [
     {
       "month":"march",
       "day":1,
       "year":2014,
       "movie":"thor"
       },
     {
       "month":"may",
       "day":29,
       "year":2020,
       "movie":"superman"
       },
     {
       "month":"may",
       "day":29,
       "year":2020,
       "movie":"batman"
       }
    ];

   var afterToday = [];

   future.forEach(function(item){
       var today = new Date();
       var zzz =  new Date(item.day + " " + item.month + " " + item.year);
       if(zzz > today)
       {
         afterToday[length] = zzz;
           $('body').append(afterToday);
       }

4 个答案:

答案 0 :(得分:1)

对于现代浏览器,请尝试

var future = [{
    "month": "march",
    "day": 1,
    "year": 2014
}, {
    "month": "may",
    "day": 29,
    "year": 2020
}, {
    "month": "may",
    "day": 16,
    "year": 2014
}];

var array = ['jan', 'feb', 'march', 'april', 'may'];
var today = new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today = today.setMilliseconds(0);
future = future.filter(function (value) {
    return new Date(value.year, array.indexOf(value.month), value.day) >= today;
})

console.log(future)

演示:Fiddle


使用jQuery交叉浏览器

future = $.grep(future, function(value){
    return new Date(value.year, $.inArray(array, value.month), value.day) > today;
})

演示:Fiddle

答案 1 :(得分:0)

您需要确定该日期的月份(0-11)的基于0的值,然后您可以splice数组中的过去日期。

jsfiddle

var future = [{
    "month": "march",
        "day": 1,
        "year": 2014
}, {
    "month": "may",
        "day": 29,
        "year": 2020
}],
    now = new Date(),
    months = [ 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december' ],
    getMonth = function(monthString) {
        return months.indexOf(monthString);
    }

for (var i in future) {
    var date = new Date(future[i].year, getMonth(future[i].month), future[i].day),
        isPast = date < now;

    if (isPast) {
        future.splice(i, 1);
    }
}

console.log(future);

答案 2 :(得分:0)

您可以将每个日期转换为可由Date.parse轻松解析的字符串。

var today = new Date();
today.setHours(0,0,0,0);

future = future.filter(function(date) {
    var parsableDate = date.month + ' ' + date.day + ', ' + date.year;
    return Date.parse(parsableDate) > today;
});

答案 3 :(得分:0)

首先,您不需要创建月份数组,因为js Date支持“2014年3月1日”等格式。 我建议你将未来的日期添加到另一个数组。

 var future =  [
     {
       "month":"march",
       "day":1,
       "year":2014
       },
     {
       "month":"may",
       "day":29,
       "year":2020
       }
    ];

   var afterToday = [];

   future.forEach(function(item){
       var today = new Date();
       var zzz =  new Date(item.day + " " + item.month + " " + item.year);
       if(zzz > today)
       {
         afterToday[length] = zzz;
       }
    });