8
5

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

JavaScriptで時間の計算をして差分の時間を表示したい

Posted at

javascriptで、
(ある時間A) ー (ある時間B) = HH:MM:SS
の形式で時間の差分を表示したかったのですが、
存外面倒で困ったのでメモ。

//test.js

let t1 = new Date();
let t2 = new Date();

let diff = t1.getTime() - t2.getTime();

//HH部分取得
let diffHour = diff / (1000 * 60 * 60);
//MM部分取得
let diffMinute = (diffHour - Math.floor(diffHour)) * 60;
//SS部分取得
let diffSecond = (diffMinute - Math.floor(diffMinute)) * 60;

console.log(('00' + Math.floor(diffHour)).slice(-2) + ':' + ('00' + Math.floor(diffMinute)).slice(-2) + ':' + ('00' + Math.round(diffSecond)).slice(-2));

このまま実行するとt1とt2の時間に差が出ないので「00:00:00」と表示されてしまいますが、
あるイベントAの直後にt1.getTime()、
あるイベントBの直後にt2.getTime()を取得するようにしてあげるとうまいこと時間の差分を取得することができます。

他に上手くやる方法はないんだろうか・・・

8
5
2

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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?