1
3

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

ユースケース

時間の差分を数値と比べたい時などに使えます。

必要なもの

・moment.js

やり方

まずはmomentオブジェクトから。
今回は時間だけを指定して作ります。

const start = moment('900', 'hmm')
const end = moment('1900', 'hmm')

diffメソッドを使って差分を取得します。
これの戻り値が数値になっています。

end.diff(start, 'hours') // 10

第3引数をtrueにすると差分が中途半端な場合でも.5など少数で返ってくるので大変便利です。

10.diff(15時30分, 'hours', true) // 5.5
10.diff(15時45分, 'hours', true) // 5.75

他にも「年」「月」などでもいけます。

end.diff(start, 'days', true)
end.diff(start, 'years', true)
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?