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
相关产品推荐
相关产品推荐

