javascript - 如何获取从过去日期到现在的月份和年份 JavaScript
问题描述
我试图弄清楚如何从过去的日期到现在获得年份和月份的组合。
所以可以说,过去的日期是
const date = "December 2019"
然后我需要一个数组
const arrayOfMonths = [ "April 2020", "March 2020", "February 2020", "January 2020", "December 2019"]
解决方案
您可以使用 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);
推荐阅读
- typescript - 泛型数组上的映射推断出错误的类型
- graphql - Graphql 响应不是来自 Apollo 客户端查询
- javafx - java.lang.NoClassDefFoundError: javafx/embed/swing/JFXPanel (Apache Felix Maven Bundle Plugin)
- visual-studio-2019 - “CTRL+逗号”搜索在 Visual Studio 2019 中不起作用
- jquery - 选择 Struts2 中的 jQuery 选项
- excel - 将 DOS 批处理文件命令转换为 VBA 函数
- java - 即使包含 User-Agent 属性,从 java 对网站的 GET 请求也会返回 403
- java - 连接到 docker 中的 postgresql 服务器时,Spring Boot 应用程序连接被拒绝
- google-sheets - 表格:在部分空的范围内查找特定值的最右边(最高列)外观的列号
- java - 构建中的 Jenkins 视图涵盖多个插件执行(插件开发)