使用Moment.js或原生JS修改ISO日期字符串并保留时区偏移的方法
实现方案
以下提供三种符合要求的实现方式,均会保留原时间及时区偏移,仅修改日期/月份:
方案1:Moment库实现(最推荐,代码量最少)
Moment解析带时区偏移的ISO字符串时会自动保留原偏移,修改日期/月份后直接输出即可,无需额外处理:
const start = '2021-09-30T06:30:00-04:00'; const date = moment(start); // 仅修改日期为29号 date.date(29); // 如需修改月份,注意month方法为0基,比如传入8代表9月、9代表10月 // date.month(7); // 修改为8月 const result = date.format(); console.log(result); // 输出:2021-09-29T06:30:00-04:00
方案2:原生JS实现(自动处理日期合法性)
如果不使用Moment,可以通过提取原偏移+日期调整的方式实现:
const start = '2021-09-30T06:30:00-04:00'; // 提取原时区偏移字符串 const tzOffset = start.match(/[+-]\d{2}:\d{2}$/)[0]; // 提取原固定时分秒 const timePart = start.split('T')[1].slice(0, 8); const date = new Date(start); // 修改日期为29号 date.setDate(29); // 如需修改月份,setMonth同样为0基 // date.setMonth(7); // 修改为8月 // 按原偏移对应的年月日格式化 const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); const result = `${year}-${month}-${day}T${timePart}${tzOffset}`; console.log(result); // 输出:2021-09-29T06:30:00-04:00
方案3:字符串拆分拼接(性能最高)
如果你已经确定新的年月日为合法值,不需要自动处理跨月、跨年逻辑,直接拆分字符串拼接是最快的方式,完全不会改动原时间和偏移部分:
const start = '2021-09-30T06:30:00-04:00'; const [, timeAndTzPart] = start.split('T'); // 替换为你需要的日期 const newDateStr = '2021-09-29'; const result = `${newDateStr}T${timeAndTzPart}`; console.log(result); // 输出:2021-09-29T06:30:00-04:00
内容的提问来源于stack exchange,提问作者WildThing
相关产品推荐
相关产品推荐

