ruby DateTime从'mm/dd/yyyy'格式解析

TKu*_*tpl 65 ruby ruby-on-rails-3

我正在使用ruby 1.9.3并希望Date or Time从' mm/dd/yyyy'日期format字符串中获取对象

Time.zone.parse("12/22/2011")
Run Code Online (Sandbox Code Playgroud)

这是给我的 *** ArgumentError Exception: argument out of range

hir*_*lau 126

require 'Date'
my_date = Date.strptime("12/22/2011", "%m/%d/%Y")
Run Code Online (Sandbox Code Playgroud)

  • 链接到APIDock文档:http://apidock.com/ruby/DateTime/strptime/class (2认同)
  • 如果字符串中有时间,请使用“DateTime”。例如 `DateTime.strptime('23/03/2020 01:01 PM', '%d/%m/%Y %l:%M %p')` (2认同)

Mit*_*tch 15

如上所述,使用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 
Run Code Online (Sandbox Code Playgroud)

(+0000是时区信息,我现在在GMT - 因此+0000.上周,在时钟回归之前,我在BST +0100.我的application.rb包含行config.time_zone ='伦敦")


Lac*_*zar 7

尝试 Time.strptime("12/22/2011", "%m/%d/%Y")


LHH*_*LHH 5

是否可以选择使用Time.strptime("01/28/2012", "%m/%d/%Y")Time.parse?这样你就可以更好地控制Ruby如何解析日期.

如果没有宝石:(例如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 
Run Code Online (Sandbox Code Playgroud)