首页 > 解决方案 > 如何获取从过去日期到现在的月份和年份 JavaScript

问题描述

我试图弄清楚如何从过去的日期到现在获得年份和月份的组合。

所以可以说,过去的日期是

const date = "December 2019"

然后我需要一个数组

const arrayOfMonths = [ "April 2020", "March 2020", "February 2020", "January 2020", "December 2019"]

标签: javascriptarraysreactjsgenerate

解决方案


您可以使用 JavaScript日期对象和 while 循环。

只需从当前月份减去一个月,直到您到达您想要的日期。

像这样的东西应该工作。

https://jsfiddle.net/wsf61jpk/5/

var date="December 2018";
var result=[];

//set both start and end date to first date of the month
const end_date = new Date(date.replace(" ", " ,1 "));
const start_date = new Date(new Date().getFullYear(), new Date().getMonth(), 1);


while(end_date<=start_date){

result.push(start_date.toLocaleString('default', { month: 'long' , year: 'numeric'}));
start_date.setMonth(start_date.getMonth() - 1);

}

console.log(result);

推荐阅读