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

JavaScript给指定ISO格式日期加时间间隔后如何返回相同格式的新日期?

问题原因

你现有代码存在两处问题:

  • 错误使用new Date()获取当前时间做计算,完全没有沿用date1的年、月、时分秒信息,导致计算基准错误
  • 没有将最终Date对象转为和date1格式匹配的ISO 8601字符串

解决方案

直接基于date1生成的Date对象做日期增减,最后调用toISOString()方法输出指定格式即可:

const newInterval = 1;
const date1 = '2022-03-02T19:16:51.433Z';
const currentDue = new Date(date1);
// 日期加1天,不影响原始currentDue的写法
const date2 = new Date(currentDue.setDate(currentDue.getDate() + newInterval)).toISOString();

console.log(date2); // 输出结果:2022-03-03T19:16:51.433Z

如果要避免修改currentDue原始值,可以调整为:

const newInterval = 1;
const date1 = '2022-03-02T19:16:51.433Z';
const currentDue = new Date(date1);
const date2 = new Date(currentDue);
date2.setDate(date2.getDate() + newInterval);
console.log(date2.toISOString());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:45:02