当前位置:网站首页>获取当前年月和之前的11个月份
获取当前年月和之前的11个月份
2022-07-21 18:08:00 【益达木咸醇】
不多说直接上代码:
function getLast12Months() {
var last12Months = [];
var today = new Date();
var year = today.getFullYear();
today.setMonth(today.getMonth());
for (var i = 0; i < 12; i++) {
last12Months[11 - i] = today.getFullYear() + '-' + fillZero(Number(today.getMonth()) + 1, 2);//这里+1是因为js 的月份是0-11
if (today.getMonth == 0) {
today.setFullYear(Number(year) - 1);
}
today.setMonth(Number(today.getMonth() - 1));
}
return last12Months;
}
//补零操作,保证月份为1位的时候补充前置0
function fillZero(num, fill) {
var len = ('' + num).length;
return (Array(fill > len ? fill - len + 1 || 0 : 0).join(0) + num);
}
这是项目中遇到的需求,在这里记下来,并且输出的格式是自己定义的,我是在这一行代码设置的输出格式:
last12Months[11 - i] = today.getFullYear() + '-' + fillZero(Number(today.getMonth()) + 1,
2); //这里+1是因为js 的月份是0-11
也可以是其他格式,如,2020:07,2020.07等等,有需要可以改一个中间的拼接字符串即可
边栏推荐
猜你喜欢
flex布局的常用属性
20201127 使用Markdown 画uml图,Graphviz 安装经历吐血整理
EAS BOS custom export (including excel style setting, multi tab export, export file directory verification and backup)
图的基本定义和概念(二)
知识分享|分享一些提升企业文档管理水平的方法
EAS web BIM start access prompt 500 error
28.接雨水
Gluttonous snake
23.螺旋矩阵
Office2016 - word cannot use input method, only English questions can be input
随机推荐
文字超出部分变成省略号的三种方式
7年违法处理近650亿条个人信息 滴滴网络安全审查案调查经过公布
uni-app接入友盟统计
微信小程序 不在以下 request 合法域名列表中
关于线程 thread (4)线程的交互
High frequency leetcode deep search part: 98 Validate binary search tree
Complete set of met settings
EAS Web 页面预览报错界面显示空白
Review of Biochemistry VII. Glucose metabolism
Generator、async 解决异步编程
正则
office2016—word不能使用输入法,只能输入英文问题
simplest-i18n
High frequency leetcode deep search part: 297 Serialization and deserialization of binary tree
36.删除链表的倒数第 N 个结点
Office2016 - word cannot use input method, only English questions can be input
flyio 无感刷新token
数组的反转(逆序输出)(定义一个数组并赋值按逆序输出这个数组)
24. 合并K个升序链表
MVP_用户登录实例2_测试用例