如何在JavaScript中以yyyymm格式获取从JAN 2022开始的所有日期?

uemypmqf  于 2023-02-28  发布在  Java
关注(0)|答案(5)|浏览(138)

我想获取从JAN 2022开始的所有日期,格式为 yyyymm。这是我的代码:

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

如何获得所需的结果?

bxgwgixi

bxgwgixi1#

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")}`);
}
neskvpey

neskvpey2#

或者你也可以用基本的代码不使用任何日期来完成

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"));
}
ghhkc1vu

ghhkc1vu3#

您可以使用.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));
}
5vf7fwbs

5vf7fwbs4#

您可以使用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);
}
mnowg1ta

mnowg1ta5#

您可以使用generators以及Intl.DateTimeFormat()

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',
        timezone: 'UTC',
    }).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',
        timezone: 'UTC',
    }).formatToParts(d).filter(p => p.type !== 'literal').map(p => p.value).join('');
  }
}
console.log([...dateRange(startDate, current)])

或者,您可以利用Array.from()

const current = Date.now();
const today = new Date();
const startDate = new Date("2022-01");
const monthsPerYear = 12;
function dateRange(startDate, current) {
  return Array.from({
      length: today.getFullYear() === startDate.getFullYear()
          ? today.getMonth() - startDate.getMonth()
          : ((monthsPerYear + 1) - today.getMonth()) + (startDate.getMonth() + 2) + ((today.getFullYear() - startDate.getFullYear() - 1) * monthsPerYear)
  }, function(v, i) {
  let date = new Date(startDate);
  date.setUTCMonth(startDate.getUTCMonth() + i)
  return `${date.getFullYear()}${(date.getMonth() + 1).toString().padStart(2, 0)}`
  });
}
console.log(dateRange(startDate, current))

相关问题