我想以 yyyymm 格式获取从 2022 年 1 月 开始的所有日期。这是我的代码:
for(var i = new Date("2022-01"); i < new Date(); i++){
console.log(i);
}
我得到这样的输出:
Sat Jan 01 2022 05:30:00 GMT+0530 (India Standard Time)
1640995200001
1640995200002...
而我想要这样的结果:
202201
202202
202203....till the current date
如何获得想要的结果?
Date
内置处理闰年和不同的月份长度。
const current = Date.now();
for (const d = new Date("2022-01"); d < current; d.setUTCMonth(d.getUTCMonth() + 1)) {
console.log(`${d.getUTCFullYear()}${(d.getUTCMonth() + 1 + "").padStart(2, "0")}`);
}
另一种方法是分别存储年份和月份。
const current = new Date();
for (
let year = 2022, month = 0;
year < current.getUTCFullYear() || month <= current.getUTCMonth();
month = (month + 1) % 12, year += month === 0
) {
console.log(`${year}${(month + 1 + "").padStart(2, "0")}`);
}
const current = Date.now();
const startDate = new Date("2022-01");
function* dateRange(startDate, current) {
for (const d = startDate; d < current; d.setUTCMonth(d.getUTCMonth() + 1)) {
yield Intl.DateTimeFormat('sv-SE', { year: 'numeric', month: '2-digit' }).format(d).replace('-', '');
}
}
console.log([...dateRange(startDate, current)])
您可以使用
Intl.DateTimeFormat()
的
formatToParts()
方法,而不是操作输出字符串:
const current = Date.now();
const startDate = new Date("2022-01");
function* dateRange(startDate, current) {
for (const d = startDate; d < current; d.setUTCMonth(d.getUTCMonth() + 1)) {
yield Intl.DateTimeFormat('sv-SE', { year: 'numeric', month: '2-digit' }).formatToParts(d).filter(p => p.type !== 'literal').map(p => p.value).join('');
}
}
console.log([...dateRange(startDate, current)])
.toISOString()
获取完整日期并将其拆分为
yyyymm
格式。
function getYYYYMM(d) {
return i.toISOString().split('T')[0].split('-').join('').slice(0,-2);
}
for(var i = new Date('2022-01'); i <= new Date(); i = new Date(i.setMonth(i.getMonth()+1))) {
console.log(getYYYYMM(i));
}
let year = 2021;
let month = 12;
while(year < 2030) // choose whatever end date you want
{
if(month == 12)
{
month = 1;
year++;
}
else
month++;
console.log(year + month.padStart(2, "0"));
}
toLocaleString
方法,使用瑞典语言环境,以便年份在前。
Date.UTC()
用于确保不同时区的日期一致:
const startDate = new Date(Date.UTC(2022, 0, 1));
const currentDate = new Date();
for (let d = startDate; d <= currentDate; d.setMonth(d.getMonth() + 1)) {
const dateStr = d.toLocaleDateString('sv-SE', { year: 'numeric', month: '2-digit' }).replace('-', '');
console.log(dateStr);
}