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

如何将事件起止日期转为当月首尾日?解决setDate不是函数问题

问题分析与解决方案

报错原因

你的start_date和end_date是字符串类型,而非JavaScript的Date对象,setDate()是Date实例专属方法,直接调用自然会报“setDate is not a function”错误。

实现思路

要完成日期转换,需要先把字符串转成Date对象,处理后再转回符合要求的字符串格式:

  • 起始日期:转成Date后,将日期设为当月1号
  • 结束日期:转成Date后,通过“月份+1,日期设为0”的方式自动获取当月最后一天(避免硬设28/30/31的兼容性问题)

完整代码示例

// 示例事件数组
const events = [
  {
    end_date: "2022-07-22T00:00:00.000Z",
    name: "Event 1",
    start_date: "2021-09-08T00:00:00.000Z"
  }
];

// 处理每个事件的日期
const processedEvents = events.map(event => {
  // 处理起始日期为当月第一天
  const startDate = new Date(event.start_date);
  startDate.setDate(1);
  const formattedStart = startDate.toISOString();

  // 处理结束日期为当月最后一天
  const endDate = new Date(event.end_date);
  // 月份+1后设日期为0,自动回退到上月最后一天(即当前月份的最后一天)
  endDate.setMonth(endDate.getMonth() + 1, 0);
  const formattedEnd = endDate.toISOString();

  return {
    ...event,
    start_date: formattedStart,
    end_date: formattedEnd
  };
});

console.log(processedEvents);

关键说明

  • 用setMonth(endDate.getMonth() + 1, 0)获取当月最后一天是通用方案,能自动适配28/29/30/31天的月份,无需手动判断月份天数。
  • 处理完成后用toISOString()转回你需要的ISO格式字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 08:25:02