js 计算时间相差

in 前端JavaScript with 0 comment

计算函数

const contDownTime = value => {
  const dayDiff = Math.floor(value / (24 * 3600)) // 计算出相差天数
  const leave1 = value % (24 * 3600) // 计算天数后剩余的毫秒数
  const hours = Math.floor(leave1 / 3600) // 计算出小时数
  const leave2 = leave1 % 3600 // 计算小时数后剩余的毫秒数
  const minutes = Math.floor(leave2 / 60) // 计算相差分钟数
  const leave3 = leave2 % 60 // 计算分钟数后剩余的毫秒数
  const seconds = Math.round(leave3)
  let t = ''

  if (dayDiff > 0) {
    t += dayDiff + "天"
  }

  if (hours > 0) {
    t += hours + "小时"
  }
  if (minutes > 0) {
    t += minutes + "分钟"
  }

  if (seconds > 0) {
    t += seconds + "秒"
  }

  if (!t) {
    return false
  }
  return t
}

两者相差

const gtDiffTime = (utcDateEnd, utcDateBegin, type = 'string') => {
  const dateDiff = moment(utcDateEnd).unix() - _moment_utc(utcDateBegin).unix() // 时间差的毫秒数
  if (type == 'number') {
    return dateDiff
  }
  if (dateDiff < 0) {
    return ''
  }
  return contDownTime(dateDiff)
}
Comments are closed.