在Ruby 1.87我可以这样做:红宝石VS 1.87 1.92 Date.parse
Date.parse ("3/21/2011")
现在1.9.2,我得到:
ArgumentError: invalid date
任何想法?
在Ruby 1.87我可以这样做:红宝石VS 1.87 1.92 Date.parse
Date.parse ("3/21/2011")
现在1.9.2,我得到:
ArgumentError: invalid date
任何想法?
使用strptime
并给出具体的时间格式。
ruby-1.9.2-p136 :022 > Date.strptime '03/21/2011', '%m/%d/%Y'
=> #<Date: 2011-03-21 (4911283/2,0,2299161)>
为Ruby版本之间的这种差异的原因见michaelmichael's response。
只是好奇,但你会如何设置红宝石的区域? – mgm8870 2011-03-21 00:03:56
看起来像你可以使用ActiveSupport的日期扩展:http://thedevelopercorner.blogspot.com/2009/03/change-default-date-format-in-ruby-on.html – 2011-03-21 00:11:50
从看日期'date/format.rb/_parse'方法,我没有看到任何检查区域设置信息。该代码采用非美国格式并首先进行检查,然后是美国。超出范围的月份值(13-31)触发该问题。最好的解决方案是知道日期来自哪个区域,然后以编程方式决定是否在Date#strptime中使用'%m /%d /%y'或'%d /%m /%y'格式。 – 2011-03-21 02:29:10
我一直很难用Date.parse
解析日期。我的解决方案是令人难以置信的chronic
gem。我也喜欢在另一个答案中找到的strptime
函数。
根据this bug report,解析mm/dd/yy
日期的能力在1.9中有意删除。 Ruby的创造者,松本行弘说:
"dd/dd/dd" format itself is very culture dependent and ambiguous. It is yy/mm/dd in Japan (and other countries), mm/dd/yy in USA, dd/mm/yy in European countries, right? In some cases, you can tell them by accident, but we should not rely on luck in general cases. I believe that is the reason parsing this format is disabled in 1.9.
由于hansengel建议,您可以使用Date.strptime
代替。
有趣。那么为什么'Date.parse('1/1/2001')'在Ruby 1.9.2-p180中工作,并出现在date.rb源代码中? 'Date.parse('1/1/2001')#=>#
@ The Tin Man,即将第一个解析为当天,第二个解析为一个月(日/月/年格式)。你只是不能说,因为他们是相同的数字;) – 2011-03-21 05:21:52
@michaelmichael,感谢您找到真正的原因。我更新了我的答案以引用您的答案,以便接受的答案具有一切正确性。 – 2011-03-21 05:28:12
class << self
def parse_with_us_format(date, *args)
if date =~ %r{^\d+/\d+/(\d+)$}
Date.strptime date, "%m/%d/#{$1.length == 4 || args.first == false ? '%Y' : '%y'}"
else
parse_without_us_format(date, *args)
end
end
alias_method_chain :parse, :us_format
end
我喜欢american_date宝石完成这个...
@bensiu,在[文档](http://rubydoc.info/stdlib/date/1.9.2/Date#parse-class_method )无助于解释问题或提供解决方法。 – 2011-03-21 02:32:41