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

如何计算距离指定精确DateTime还剩余的天数、小时与分钟数

倒计时剩余时分秒计算方案

要计算剩余小时、分钟,只需要在总时间差的基础上做取模运算,扣除已计入天数的时间部分后拆分即可,具体实现逻辑如下:

核心计算规则

  • 先获取目标时间戳与当前时间戳的差值,单位为毫秒,记为diffMs,如果差值为负说明目标时间已过期
  • 剩余天数 = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  • 扣除天数对应的毫秒数后,剩余部分计算小时:Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  • 扣除小时对应的毫秒数后,剩余部分计算分钟:Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
  • 如有需要还可以继续计算秒数:Math.floor((diffMs % (1000 * 60)) / 1000)

代码示例(JavaScript)

function getCountdown(targetTime) {
  const now = Date.now()
  const diffMs = Math.max(targetTime - now, 0) // 差值为0时表示已到期
  const days = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((diffMs % (1000 * 60)) / 1000)
  return { days, hours, minutes, seconds }
}

// 调用示例:计算到2024年12月31日的倒计时
const target = new Date('2024-12-31T23:59:59').getTime()
const countdown = getCountdown(target)
console.log(`剩余 ${countdown.days} 天 ${countdown.hours} 小时 ${countdown.minutes} 分钟 ${countdown.seconds} 秒`)

实现效果示例

example picture

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:45:05