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

JavaScript:将对象数组中的日期转换为上下半年格式

问题:将对象数组中的日期字符串转换为上下半年格式

当前数据集

// Current Data set 
data = [
    {'description': 'halfyear', date: '2024.01.01'},
    {'description': 'halfyear', date: '2024.07.01'},
    {'description': 'halfyear', date: '2016.01.01'},
    {'description': 'halfyear', date: '2016.07.01'}
]

期望转换结果

// Expected Data 
data = [
    {'description': 'halfyear', date: 'H1\'2024'},
    {'description': 'halfyear', date: 'H2\'2024'},
    {'description': 'halfyear', date: 'H1\'2016'},
    {'description': 'halfyear', date: 'H2\'2016'}
]

你尝试的错误代码

data.map(x=> {
 return x.formatted = 'H' + ' ' + new Date(x.date).getMonth() + 1 < 6 ? '1': '2' + new Date(x.date).getFullYear() + ''
})

问题分析与修正方案

你的代码存在几个关键问题:

  1. 运算符优先级错误:new Date(x.date).getMonth() + 1 < 6 中,+的优先级高于<,导致实际计算的是getMonth() + (1 < 6),而非(getMonth()+1) < 6,逻辑完全错误。
  2. 日期解析兼容性问题:直接用new Date('2024.01.01')可能在部分浏览器中解析失败,因为.不是标准日期分隔符,建议替换为-。
  3. 字符串拼接逻辑混乱:三元运算符的分支未正确关联年份拼接,且你需要更新原对象的date字段,而非新增formatted字段。

正确代码

const convertedData = data.map(item => {
    // 替换日期分隔符,确保跨浏览器解析正确
    const dateStr = item.date.replace(/\./g, '-');
    const date = new Date(dateStr);
    const month = date.getMonth() + 1; // 转换为1-12月
    const year = date.getFullYear();
    // 判断上下半年并拼接目标格式
    const halfYear = month <= 6 ? `H1'${year}` : `H2'${year}`;
    // 返回新对象(若要直接修改原数组,可改为 item.date = halfYear; return item;)
    return { ...item, date: halfYear };
});

console.log(convertedData);

代码说明

  • 用正则替换把所有.换成-,保证new Date能正确解析日期。
  • getMonth()返回0-11,加1后得到实际的1-12月,方便判断上下半年。
  • 使用模板字符串简化拼接逻辑,避免字符串拼接的优先级问题。
  • 用扩展运算符{ ...item }创建新对象,不修改原数组元素(如需直接修改原数组,可去掉扩展运算符,直接给item.date赋值)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 02:52:24