You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript获取2022年1月起的yyyymm格式日期

解决方法

你的问题出在循环步长和日期格式化上:原来的i++会给Date对象每次加1毫秒,导致输出连续的时间点,而非按月遍历。以下是实现需求的代码:

const now = new Date();
const currentYear = now.getFullYear();
const currentMonth = now.getMonth() + 1; // 月份从0开始计数,需加1转为实际月份

// 初始化起始日期为2022年1月
for (let date = new Date("2022-01"); ; date.setMonth(date.getMonth() + 1)) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    
    // 格式化为yyyymm,月份不足两位补0
    const formattedDate = `${year}${month.toString().padStart(2, '0')}`;
    console.log(formattedDate);
    
    // 到达当前月份时终止循环
    if (year === currentYear && month === currentMonth) {
        break;
    }
}

关键说明

  • 按月推进日期:用date.setMonth(date.getMonth() + 1)替代i++,确保每次循环跳转到下一个月
  • 日期格式化:
    • getFullYear()获取四位年份
    • getMonth()返回0-11的数值,加1得到实际月份后,用padStart(2, '0')补前导零,保证月份是两位数字(如1月转为01)
  • 终止条件:判断当前循环的年月是否等于系统当前年月,避免输出超出当前月份的结果

内容的提问来源于stack exchange,提问作者user21271268

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 20:45:37