LoginSignup
2
0

More than 3 years have passed since last update.

【Ruby】Date型、DateTime型の計算

Last updated at Posted at 2019-06-01

簡単なのに忘れがちなDate型、DateTime型の計算方法について。
計算方法というよりは計算結果についての備忘録だけど。
( ※ 計算結果は2019-06-01 時点 )

実行環境
Ruby 2.5.1

Date型の計算

誕生日から今日までの経過日数を計算する

require 'date'

today = Date.today()
birthday = Date.new(1985, 11, 27)

days = today - birthday
#=> (12239/1)

Date型の計算結果は「日数」で得られる。
ということでこの世に生を受けて12239日経過していることがわかったが、なぜか整数ではなく分数のような形で出力されている。
試しにデータ型を調べる。


today.class
#=> Date

birthday.class
#=> Date

days.class
#=> Rational

Rational型?
初見だったのでリファレンスで確認してみた。
Ruby 2.6.0 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Rationalクラス

有理数??
理系出身のはずなのに記憶が蘇ってこない、、、
助けてGoogle先生!

【有理数とは】実数のうち、整数か分数かの形で表せる数の総称。

なるほど。
ということで、整数型にしたければ単純に to_i してあげれば良さそう。

days.to_i
#=> 12239

DateTime型の計算

1日の勤務時間を計算する

require 'date'

work_from = DateTime.new(2019, 06, 01, 10, 00, 00)
work_to = DateTime.new(2019, 06, 01, 18, 00, 00)

work_times = work_to - work_from
#=> (1/3)

DateTime型も計算結果は「日数」で得られる。
そしてもちろんRational型。

勤務時間(h)を得たければ24を掛ける。

(work_times * 24).to_f
#=> 8.0

以上。

2
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
2
0