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

如何在JavaScript中将年月(YYYYmm)字符串转换为DateTime?

年月字符串转指定DateTime格式的实现方法

原生JavaScript实现

如果项目未引入第三方日期库,原生JS通过字符串拆分+拼接就能高效实现:

const yearMonth = "202008";
// 拆分年份和月份
const year = yearMonth.substring(0, 4);
const month = yearMonth.substring(4, 6);
// 直接拼接目标格式(格式固定,无需复杂计算)
const formattedDateTime = `${year}-${month}-01 00:00:00`;
console.log(formattedDateTime); // 输出 "2020-08-01 00:00:00"

如果需要生成实际Date对象用于后续操作,可补充构造:

const dateObj = new Date(year, month - 1, 1, 0, 0, 0);
// 从Date对象转成目标字符串
const formattedFromDate = dateObj.toISOString().replace('T', ' ').slice(0, 19);
console.log(formattedFromDate); // 输出 "2020-08-01 00:00:00"

Moment.js实现

若项目已引入Moment.js,代码会更简洁直观,无需手动处理月份索引问题:

const yearMonth = "202008";
const formattedDateTime = moment(yearMonth, "YYYYMM").format("YYYY-MM-DD HH:mm:ss");
console.log(formattedDateTime); // 输出 "2020-08-01 00:00:00"

Moment.js会自动将未指定的日期、时间部分设为默认值(日期为当月1号,时分秒为0)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:46:57