0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】2つの日時データの差を、日・時・分・秒に分けて求める

Posted at

内容

二つの日時データ(Dateオブジェクト)の差を求めて、
残り時間は、あと何日と何時間 何分 何秒です! とか表示したくて。
毎度苦労するので、形に残しておこうと思いました。

コード

ずいぶん泥臭い書き方になってしまいました。。
日付を二つ引数で渡しますが、どちらが先の日付・後の日付でも構わないよう、
差を絶対値にしています。

/** 1日の秒数 */
const DAY_TO_SEC = 60 * 60 * 24;

/** 1時間の秒数 */
const HOUR_TO_SEC = 60 * 60;

/** 1分の秒数 */
const MIN_TO_SEC = 60;

/**
 * 二つの日時データの差を、日・時・分・秒に分解して求める。
 *
 * @param time1 比較したい日時:その1
 * @param time2 比較したい日時:その2
 * @returns { day: 日数の差; hour: 時間の差; minutes: 分の差; sec: 秒の差 }
 */
export function calcTimeDifference(
  time1: Date,
  time2: Date
): { day: number; hour: number; minutes: number; sec: number } {
  // 秒単位での差を求める・・・UNIXタイムからミリ秒部分を削って、以後の計算に利用する
  let diffBySec = 
    Math.abs(Math.floor(time1.getTime() / 1000)
    - Math.floor(time2.getTime() / 1000));

  // 何日差か計算
  const dateDiff = Math.floor(diffBySec / DAY_TO_SEC);

  // 何時間差か計算
  diffBySec = diffBySec - dateDiff * DAY_TO_SEC;
  const hourDiff = Math.floor(diffBySec / HOUR_TO_SEC);

  // 何分差か計算
  diffBySec = diffBySec - hourDiff * HOUR_TO_SEC;
  const minDiff = Math.floor(diffBySec / MIN_TO_SEC);

  // 何秒差か計算
  diffBySec = diffBySec - minDiff * MIN_TO_SEC;
  const secDiff = diffBySec;

  return {
    day: dateDiff,
    hour: hourDiff,
    minutes: minDiff,
    sec: secDiff
  };
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?