March 27, 2020

JavaScript 倒计时

使用 moment 来简化输入的时间格式化过程。

import moment from "moment";

export const fromNow = (time, format = 'HH:mm:ss') => {
  const _format = (value = {}) => format
    .replace('HH', value.HH || '00')
    .replace('mm', value.mm || '00')
    .replace('ss', value.ss || '00')
    .replace('H', value.H || '0')
    .replace('m', value.m || '0')
    .replace('s', value.s || '0');

  if (!time) {
    return _format();
  }

  const diff = moment(time).diff(moment());
  
  if (diff <= 0) {
    return _format();
  }
  
  const hoursScale = 1000 * 60 * 60;
  const minutesScale = 1000 * 60;
  const secondsScale = 1000;

  const hours = parseInt(diff / hoursScale);
  const minutes = parseInt((diff - hours * hoursScale) / minutesScale);
  const seconds = parseInt(
    (diff - hours * hoursScale - minutes * minutesScale) / secondsScale
  );

  const patchHours = hours < 10 ? '0' + hours : hours;
  const patchMinutes = minutes < 10 ? '0' + minutes : minutes;
  const patchSeconds = seconds < 10 ? '0' + seconds : seconds;

  return _format({
    HH: patchHours,
    mm: patchMinutes,
    ss: patchSeconds,
    H: hours,
    m: minutes,
    s: seconds
  });
}