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

JavaScript中如何将202001类日期值转换为January_2020格式?

JavaScript实现6位年月字符串转月份英文全称+年份格式

实现逻辑

  • 拆分6位输入:前4位为年份,后2位为月份数值
  • 匹配1-12月对应的英文名称
  • 按月份名_年份格式拼接结果

基础实现(手动维护月份映射,兼容性最好)

function formatYearMonth(dateStr) {
  // 输入合法性校验
  if (!/^\d{6}$/.test(dateStr)) throw new Error('请输入6位数字格式的年月字符串');
  const year = dateStr.slice(0, 4);
  const month = Number(dateStr.slice(4, 6));
  if (month < 1 || month > 12) throw new Error('月份取值范围为1-12');

  const monthEnNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  return `${monthEnNames[month - 1]}_${year}`;
}

// 测试用例
console.log(formatYearMonth('202001')); // 输出 January_2020

内置API实现(无需手动维护月份名,支持多语言拓展)

借助Intl.DateTimeFormat内置API直接获取英文月份全称,不需要手动写映射数组:

function formatYearMonth(dateStr) {
  if (!/^\d{6}$/.test(dateStr)) throw new Error('请输入6位数字格式的年月字符串');
  const year = Number(dateStr.slice(0, 4));
  const month = Number(dateStr.slice(4, 6)) - 1; // Date实例月份从0开始计数
  const monthName = new Intl.DateTimeFormat('en-US', { month: 'long' }).format(new Date(year, month));
  return `${monthName}_${year}`;
}

// 测试用例
console.log(formatYearMonth('202001')); // 输出 January_2020

内容的提问来源于stack exchange,提问作者Ashish good luck chuck

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 04:06:05