2024年04月02日 前端 JS JavaScript 共享博客
最近做项目,需要获取到近30天的日期来获取对应的内容,如下图
写了个demo,加了些拼接判断,拼接成 01-01这种类型,如下代码,代码有点杂乱,反正需求是出来了,如果有什么更简单的,欢迎评论留言。
// 获取月日 let times = new Date(); let Y = times.getFullYear(); let M = times.getMonth() + 1; let D = times.getDate(); let MD = ""; let dateArr = []; for (let i = 0; i <= 30-1; i++) { if (D - i > 0) { var E = M; if(E === 0 || E === 1 || E === 2 || E === 3 || E === 4 || E === 5 || E === 6 || E === 7 || E === 8 || E === 9){ if( E < 10 ){ E = '0' + E } } var F = D - i; if(F === 0 || F === 1 || F === 2 || F === 3 || F === 4 || F === 5 || F === 6 || F === 7 || F === 8 || F === 9){ if( F < 10 ){ F = '0' + F } } MD = E + "月" + F + "日"; dateArr[i] = MD; } else { M = times.getMonth(); if (M == 1 || M == 3 || M == 5 || M == 7 || M == 8 || M == 10 || M == 12) { if(M === 0 || M === 1 || M === 2 || M === 3 || M === 4 || M === 5 || M === 6 || M === 7 || M === 8 || M === 9){ if( M < 10 ){ M = '0' + M } } var F = D - i + 31; if(F === 0 || F === 1 || F === 2 || F === 3 || F === 4 || F === 5 || F === 6 || F === 7 || F === 8 || F === 9){ if( F < 10 ){ F = '0' + F } } MD = M + "月" + F + "日"; } else if (M == 4 || M == 6 || M == 9 || M == 11) { if(M === 0 || M === 1 || M === 2 || M === 3 || M === 4 || M === 5 || M === 6 || M === 7 || M === 8 || M === 9){ if( M < 10 ){ M = '0' + M } } var F = D - i + 30; if(F === 0 || F === 1 || F === 2 || F === 3 || F === 4 || F === 5 || F === 6 || F === 7 || F === 8 || F === 9){ if( F < 10 ){ F = '0' + F } } MD = M + "月" + F + "日"; } else { if (((Y % 4) == 0) && ((Y % 100) != 0) || ((Y % 400) == 0)) { //闰年 if(M === 0 || M === 1 || M === 2 || M === 3 || M === 4 || M === 5 || M === 6 || M === 7 || M === 8 || M === 9){ if( M < 10 ){ M = '0' + M } } var F = D - i + 29; if(F === 0 || F === 1 || F === 2 || F === 3 || F === 4 || F === 5 || F === 6 || F === 7 || F === 8 || F === 9){ if( F < 10 ){ F = '0' + F } } MD = M + "月" + F + "日"; } else { if(M === 0 || M === 1 || M === 2 || M === 3 || M === 4 || M === 5 || M === 6 || M === 7 || M === 8 || M === 9){ if( M < 10 ){ M = '0' + M } } var F = D - i + 28; if(F === 0 || F === 1 || F === 2 || F === 3 || F === 4 || F === 5 || F === 6 || F === 7 || F === 8 || F === 9){ if( F < 10 ){ F = '0' + F } } MD = M + "月" + F + "日"; } } dateArr[i] = MD; this.dangqianriqi = dateArr[0]; // 今日日期 } }
最后,我们可以打印下 dataArr ,结果如下
本文链接:http://so.lmcjl.com/news/978/