LoginSignup
47
41

More than 5 years have passed since last update.

Time.parse と Time.zone.parse の違い

Last updated at Posted at 2013-10-29

Time.parseTime.zone.parse に置き換えようとしたら、正しくない日付文字列を与えた時の動作がちがったので試してみた

環境は Ruby 2.0.0-p247 と ActiveSupport 4.0.0

Time.parse

Time.parse('2013/10/01')
=> 2013-10-01 00:00:00 +0900
Time.parse('2013/10/01').class
=> Time
Time.parse('hoge')
ArgumentError: no time information in "hoge"
Time.parse('2013/99/99')
ArgumentError: argument out of range

Time.zone.parse

Time.zone.parse('2013/10/01')
=> Tue, 01 Oct 2013 00:00:00 JST +09:00
Time.zone.parse('2013/10/01').class
=> ActiveSupport::TimeWithZone
Time.zone.parse('hoge')
=> nil
Time.zone.parse('2013/99/99')
ArgumentError: invalid date

結果

Time.zone.parse に正しくない日付を渡した時には nil になったり例外が起きたりする

ソースコードをみると Date._parse を使っているようだ
https://github.com/rails/rails/blob/4-0-stable/activesupport/lib/active_support/values/time_zone.rb#L282

Date._parse

Date._parse('2013/99/99')
=> {:year=>2013, :mon=>99, :mday=>99}

なるほど〜

使うときは

time = Time.zone.parse(string) rescue nil
... unless time

とかすればよいのかしら…

47
41
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
47
41