在JSON变量循环中获取最近5年的日期

时间:2013-11-28 03:30:05

标签: javascript jquery json

我想知道如何从JSON变量中检索过去5年和过去10年的日期,其格式如下。

var dates = 

"[{\"Date\":\"1996-05-31T00:00:00\"},{"Date\":\"1996-06-30T00:00:00\"},{\"Date\":\"1996-07-31T00:00:00\"},{\"Date\":\"1996-08-31T00:00:00\"},{"Date\":\"1996-09-30T00:00:00\"},{\"Date\":\"1996-10-31T00:00:00\"} ...
{\"Date\":\"2013-08-31T00:00:00\"},{"Date\":\"2013-09-30T00:00:00\"},{\"Date\":\"2013-10-31T00:00:00\"}]"

note ...是因为空间而中断所有变量的地方。

这是我到目前为止所做的:

var data = JSON.parse(dates);

var d1 = [] d2 = [], d3 [];

var today = new Date();today.setHours(0,0,0,0);
var last5Years = new Date(today.setFullYear(today.getFullYear() -5)).getTime();
var last10Years = new Date(today.setFullYear(today.getFullYear() - 10)).getTime();

for (i = 0; i < data.length; i++) {
  var s = data[i].Date.split('T')[0];
  var t = [new Date(s).getTime()];
  d1.push(t);  // all dates
  if (t[0] > last5Years) {
   d2.push(t); //push last 5years dates to d2
  }
 else if (t[0] > last10Years) { 
   d3.push(t); //push last 10 years dates to d3
 }
}

d2似乎有效但d3由于某种原因不正确。

提前致谢

1 个答案:

答案 0 :(得分:1)

1)获取 today's date ,如下所示

var today = new Date();  //returns dateTime
today.setHours(0,0,0,0); //reset time to zero to get only the date part

2)要回到 5年前,请进行设置。

var last5Years = new Date(today.setFullYear(today.getFullYear() + 5)).getTime();

3)现在让回到10年,再次减少今天的年份 5(不是10) 并设置它。

var last10Years = new Date(today.setFullYear(today.getFullYear() + 5)).getTime();

4)由于您已经在json中解析了日期,只需添加以下条件

var s = data[i].Date.split('T')[0];
    var t = [new Date(s).getTime()];
    d1.push(t);  //push all dates to d1
    if (t < last5Years) { 
        d2.push(t); //push last 5years dates to d2
    }
    else if (t < last10Years) { 
        d3.push(t); //push last 10 years dates to d3
    }

最后你的代码将是

var data = JSON.parse(dates);
var d1 = [], d2 = [], d3 = [];
for (var i = 0; i<data.length;i++) {
    var today = new Date();
    today.setHours(0,0,0,0);
    //Get time of last 5 years
    var last5Years = new Date(today.setFullYear(today.getFullYear() + 5)).getTime();
    //Get time of last 10 years
    var last10Years = new Date(today.setFullYear(today.getFullYear() + 5)).getTime();
    var s = data[i].Date.split('T')[0];
    var t = [new Date(s).getTime()];
    d1.push(t);  //push all dates to d1
    if (t < last5Years) { 
        d2.push(t); //push last 5years dates to d2
    }
    else if (t < last10Years) { 
        d3.push(t); //push last 10 years dates to d3
    }
}

希望你明白。