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

如何在JavaScript/TypeScript中将当前日期的时间替换为指定时间

实现方案

你之前的写法是将当前时间的时间戳与自定义时间对应的毫秒数相加,得到的是当前时间延后自定义时长的结果,自然不符合替换时间的需求,可按以下两种方案实现:

方案1:沿用你已有的convertTimeToInt方法

如果你的convertTimeToInt方法返回的是自定义时间距离当日0点的毫秒数,可以直接用以下逻辑:

// 获取当日0点的时间戳,自动保留当前的年/月/日
const todayStartTimestamp = new Date(new Date().toDateString()).getTime()
// 叠加自定义时间的毫秒数,得到替换后目标时间的时间戳
const targetTimestamp = todayStartTimestamp + convertTimeToInt(this.timeInput)
const targetDate = new Date(targetTimestamp)

方案2:直接解析时间输入(无需依赖自定义转换方法)

如果不想依赖convertTimeToInt,可以直接解析自定义时间后和当前日期拼接:

const customTime = this.timeInput // 输入示例:05:17 am
// 解析12小时制时间
const [timeStr, period] = customTime.trim().split(' ')
let [hours, minutes] = timeStr.split(':').map(Number)
// 12小时制转24小时制
if (period.toLowerCase() === 'pm' && hours < 12) hours += 12
if (period.toLowerCase() === 'am' && hours === 12) hours = 0

// 直接替换当前日期的时分部分
const now = new Date()
const targetDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hours, minutes, 0)

格式化输出示例

如果需要输出和示例一致的MM-DD-YYYY hh:mm a格式,可以用以下格式化方法:

function formatTargetDate(date) {
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const year = date.getFullYear()
  const hours = date.getHours()
  const showHours = hours % 12 || 12
  const showPeriod = hours >= 12 ? 'pm' : 'am'
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${month}-${day}-${year} ${showHours}:${minutes} ${showPeriod}`
}

// 调用后即可得到预期输出
console.log(formatTargetDate(targetDate))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 04:18:05