Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
38
Help us understand the problem. What is going on with this article?
@slightair

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

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

なるほど〜

使うときは

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

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

38
Help us understand the problem. What is going on with this article?
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

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
38
Help us understand the problem. What is going on with this article?