현재 시간부터 목표 시간까지 남은 시간 계산 — Date 끼리 빼면 숫자 문맥에서 타임스탬프(ms)로 바뀌어 차가 밀리초로 나온다.1

function calculateRemainingTime(targetTime) {
  const now = new Date()
  const [h, m, s] = targetTime.split(':').map(Number)

  const target = new Date()
  target.setHours(h, m, s)

  const diff = target - now
  if (diff < 0) return null

  return {
    hours: Math.floor(diff / 3600000) % 24,
    minutes: Math.floor(diff / 60000) % 60,
    seconds: Math.floor(diff / 1000) % 60,
  }
}

calculateRemainingTime('18:30:00')
// { hours: 2, minutes: 15, seconds: 30 }

Footnotes

  1. Date — MDN: “The valueOf() and Symbol.toPrimitive (when passed “number”) methods — which are automatically called in number coercion — return the timestamp, causing Date objects to behave like their timestamps when used in number contexts.“ ↩

`#531`