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 3 years have passed since last update.

TypeScriptで2つのDateの秒差を返す

Posted at

TypeScriptで,2つのDateから秒の差を返す処理を備忘録として記載します.

環境

  • TypeScript 4.5.4

仕様

  • 2つの Date 型を引数として,秒の差を算出する
  • 返却値は number 型で返す
  • マイナスの number 値を返す場合あり
  • 端数としてミリ秒が発生する場合は切り捨て処理を行う

秒の差を返す関数を実装

export const calcDifferenceSecond = (targetDateTime: Date, compareDateTime: Date) :number => {
    let diffMilliSecond = targetDateTime.getTime() - compareDateTime.getTime();

    // ミリセカンドから秒に変換して返す
    return Math.floor(diffMilliSecond / 1000);
}

基本的には Date 形式のデータを getTime() を用いてUNIXエポックからの経過ミリ秒( 1970-01-01 00:00:00 からの経過ミリ秒)に変換した後に,差分を求めます.

ミリ秒同士で差分を算出するため,値を返すときに 1000 を割って秒に変換しています.

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?