2011-03-20 51 views
47

在Ruby 1.87我可以这样做:红宝石VS 1.87 1.92 Date.parse

Date.parse ("3/21/2011") 

现在1.9.2,我得到:

ArgumentError: invalid date

任何想法?

+4

@bensiu,在[文档](http://rubydoc.info/stdlib/date/1.9.2/Date#parse-class_method )无助于解释问题或提供解决方法。 – 2011-03-21 02:32:41

回答

60

使用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

+0

只是好奇,但你会如何设置红宝石的区域? – mgm8870 2011-03-21 00:03:56

+0

看起来像你可以使用ActiveSupport的日期扩展:http://thedevelopercorner.blogspot.com/2009/03/change-default-date-format-in-ruby-on.html – 2011-03-21 00:11:50

+1

从看日期'date/format.rb/_parse'方法,我没有看到任何检查区域设置信息。该代码采用非美国格式并首先进行检查,然后是美国。超出范围的月份值(13-31)触发该问题。最好的解决方案是知道日期来自哪个区域,然后以编程方式决定是否在Date#strptime中使用'%m /%d /%y'或'%d /%m /%y'格式。 – 2011-03-21 02:29:10

2

我一直很难用Date.parse解析日期。我的解决方案是令人难以置信的chronic gem。我也喜欢在另一个答案中找到的strptime函数。

25

根据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代替。

+0

有趣。那么为什么'Date.parse('1/1/2001')'在Ruby 1.9.2-p180中工作,并出现在date.rb源代码中? 'Date.parse('1/1/2001')#=>#','RUBY_VERSION#=>“1.9.2”'[ Date.parse'](http://rubydoc.info/stdlib/date/1.9.2/Date#parse-class_method) – 2011-03-21 02:15:56

+0

@ The Tin Man,即将第一个解析为当天,第二个解析为一个月(日/月/年格式)。你只是不能说,因为他们是相同的数字;) – 2011-03-21 05:21:52

+0

@michaelmichael,感谢您找到真正的原因。我更新了我的答案以引用您的答案,以便接受的答案具有一切正确性。 – 2011-03-21 05:28:12

1
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 
2

我喜欢american_date宝石完成这个...

+0

为什么这个解决方案感觉很脏?我试图修改我的代码以使用Time.strptime(...),但遇到了JQuery datepicker和PostgreSQL数据库格式的级联问题。浪费时间。但是,宝石完美的工作......只是觉得肮脏和肮脏......期待这个问题在未来再次出现! – vanboom 2013-06-22 23:00:57

+0

@vanboom是的,这有点奇怪,但是这个宝石的作者是Ruby日期的权威,所以如果他写了一个宝石,显然是必要的。 – Dex 2013-07-19 23:39:45