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

JavaScript如何将日期字符串数组转换为带year/month/day属性的对象数组

实现代码

你可以直接通过数组map方法配合字符串拆分实现转换:

// 原始日期字符串数组
const dateArr = ["2021-11-01","2021-11-02"];

// 转换逻辑
const formattedArr = dateArr.map(item => {
  // 按-拆分日期字符串,分别赋值给年、月、日
  const [year, month, day] = item.split('-');
  return {
    year: Number(year),
    month: Number(month),
    // 如果需要day为数字类型就改成Number(day),输出为1、2;保留01格式直接用day变量即可,类型为字符串
    day: day
  }
})

console.log(formattedArr);
// 输出结果:[{ year: 2021, month: 11, day: '01' }, { year: 2021, month: 11, day: '02' }]

补充说明

如果你需要year、month、day全为数字类型,简化写法如下:

const formattedArr = dateArr.map(item => {
  const [year, month, day] = item.split('-').map(Number);
  return { year, month, day }
})
// 输出:[{ year: 2021, month: 11, day: 1 }, { year: 2021, month: 11, day: 2 }]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:36:03