ruby DateTime 从'mm/dd/yyyy'格式解析
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19643444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ruby DateTime parsing from 'mm/dd/yyyy' format
提问by TKumar Stpl
I am using ruby 1.9.3and want to get Date or Timeobject from 'mm/dd/yyyy' date formatstring
我正在使用ruby 1.9.3并想Date or Time从 ' mm/dd/yyyy' 日期format字符串中获取对象
Time.zone.parse("12/22/2011")
this is giving me *** ArgumentError Exception: argument out of range
这给了我 *** ArgumentError Exception: argument out of range
回答by hirolau
require 'Date'
my_date = Date.strptime("12/22/2011", "%m/%d/%Y")
回答by Mitch
As above, use the strptime method, but note the differences below
同上,使用strptime方法,但注意下面的区别
Date.strptime("12/22/2011", "%m/%d/%Y") => Thu, 22 Dec 2011
DateTime.strptime("12/22/2011", "%m/%d/%Y") => Thu, 22 Dec 2011 00:00:00 +0000
Time.strptime("12/22/2011", "%m/%d/%Y") => 2011-12-22 00:00:00 +0000
(the +0000 is the timezone info, and I'm now in GMT - hence +0000. Last week, before the clocks went back, I was in BST +0100. My application.rb contains the line config.time_zone = 'London')
(+0000 是时区信息,我现在在 GMT - 因此是 +0000。上周,在时钟返回之前,我在 BST +0100。我的 application.rb 包含行 config.time_zone = 'London ')
回答by Lachezar
Try Time.strptime("12/22/2011", "%m/%d/%Y")
尝试 Time.strptime("12/22/2011", "%m/%d/%Y")
回答by LHH
Would it be an option for you to use Time.strptime("01/28/2012", "%m/%d/%Y")in place of Time.parse? That way you have better control over how Ruby is going to parse the date.
您可以选择使用它来Time.strptime("01/28/2012", "%m/%d/%Y")代替 Time.parse 吗?这样你就可以更好地控制 Ruby 将如何解析日期。
If not there are gems: (e.g. ruby-american_date) to make the Ruby 1.9 Time.parse behave like Ruby 1.8.7, but only use it if it's absolutely necessary.
如果没有,则使用 gems:(例如 ruby-american_date)使 Ruby 1.9 Time.parse 的行为类似于 Ruby 1.8.7,但仅在绝对必要时才使用它。
1.9.3-p0 :002 > Time.parse '01/28/2012'
ArgumentError: argument out of range
1.9.3-p0 :003 > require 'american_date'
1.9.3-p0 :004 > Time.parse '01/28/2012'
=> 2012-01-28 00:00:00 +0000

