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

在JavaScript(React)中合并Moment DateTime对象的日期与时间

解决方案

方法1:直接操作moment对象属性(最优)

不需要转字符串拼接,直接基于moment原生API实现,性能最高,也不会出现格式、时区、月份取值错误的问题:

// 先克隆原始date对象,避免修改原对象的值
const mergedDateTime = date.clone().set({
  hour: time.get('hour'),
  minute: time.get('minute'),
  second: time.get('second'),
  millisecond: time.get('millisecond')
})

如果需要做非空兼容,可以加可选链和默认值兜底:

const mergedDateTime = date?.clone()?.set({
  hour: time?.get('hour') ?? 0,
  minute: time?.get('minute') ?? 0,
  second: time?.get('second') ?? 0,
  millisecond: time?.get('millisecond') ?? 0
})

方法2:格式化字符串拼接

如果更习惯用字符串拼接的方式,可以用format方法统一处理格式,避免手动拼接出现的月份错误问题(moment的get('month')返回0基数值,直接拼接会导致月份偏移1个月):

const mergedDateTime = moment(`${date.format('YYYY-MM-DD')} ${time.format('HH:mm:ss.SSS')}`)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 20:45:01