Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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

http://doc.ruby-lang.org/ja/2.0.0/class/Date.html#S__PARSE

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

なるほど〜

使うときは

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

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away