如何获得当前日期的最后几个月和几年

时间:2017-06-28 10:12:35

标签: javascript arrays json

我想创建如下所示格式化的JSON,从当前日期开始按降序排列(它将是实际的当前日期)。

var theMonths = [
 {"date":"2015-12","value":null}, {"date":"2016-01","value":null},   
 {"date":"2016-02","value":null}, {"date":"2016-03","value":null},
 {"date":"2016-04","value":null}, {"date":"2016-05","value":null},
 {"date":"2016-06","value":null}, {"date":"2016-07","value":null},
 {"date":"2016-08","value":null}, {"date":"2016-09","value":null},
 {"date":"2016-10","value":null}, {"date":"2016-11","value":null},
 {"date":"2016-12","value":null}, {"date":"2017-01","value":null},
 {"date":"2017-02","value":null}, {"date":"2017-03","value":null},
 {"date":"2017-04","value":null}, {"date":"2017-05","value":null}
]

我想在图表中传递这些数据。

1 个答案:

答案 0 :(得分:0)

var dateFromPast = [];

var amountOfDatesFromPast = 18; for(var i = 0; i< amountOfDatesFromPast; i ++){

var dateObj = new Date();
dateObj.setMonth(dateObj.getMonth() - i);
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var year = dateObj.getUTCFullYear();

newdate = year + "-" + month;
dateFromPast.push(newdate);

} 的console.log(dateFromPast);