LoginSignup
15
8

More than 3 years have passed since last update.

[Ruby]Time型,Date型から文字列への変換、日付の比較

Posted at

TimeとかDateとかニガテ

RubyのTime型やDate型に疎いので、これらの変換に関してメモ。

文字列をTime型やDate型にする

Time.parseDate.parseを使う。
to_dateを使うとTime型からDate型に変換できる。
to_timeは一度Date型にしてしまうと時刻を失うので、00:00:00になる。

str_time = '2020-01-01 12:00:00'
Time.parse(str_time)
#=> 2020-01-01 12:00:00 +0900
Date.parse(str_time)
#=> #<Date: 2020-01-01 ((2458850j,0s,0n),+0s,2299161j)>
Time.parse(str_time).to_date
#=> #<Date: 2020-01-01 ((2458850j,0s,0n),+0s,2299161j)>
Date.parse(str_time).to_time
#=> 2020-01-01 00:00:00 +0900

14桁の数字をTime型に

DBに保存する際は、'2020-01-01 12:00:00'ではなく'2020010112000000'とする場合もある。
DBから取り出した14桁の数字をTime型にしたい。

int_time = 2020010112000000
str_int_time = int_time.to_s
#=> '2020010112000000'
fix_str_int_time = str_int_time.insert(8, " ")
#=> '20200101 12000000'
str_int_time_to_time = Time.parse(fix_str_int_time)
#=> '2020-01-01 12:00:00 +0900'

'2020010112000000'これのまま変換しようとすると
'2020-01-01 00:00:00 +0900'と時刻が反映されなくなるので注意。

反対に14桁の数字の文字列をDBに保存する場合はstrftimeメソッドを使う。

str_int_time_to_time.strftime("%Y%m%d%H%M%S")
#=> '2020010112000000'

日付の比較

Time型のものはto_dateメソッドを使用してDate型で比較する。

current_date = current_time.to_date
current_date.prev_day(5) < Date.today
#=> true

prev_day(n)はn日前
next_day(n)はn日後

おわりに

時間関連がでてくると実装を後回しにしまいがちな自分がいたので、簡単な変換を整理しました。
次のことを明確に確認しました。
- 14桁の数字の文字列は日付と時刻の間に空白がないと上手くいかない
- 日付の比較はTime型をto_dateすれば、不等号で比較ができる

こんなところでしょうか。

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