Ruby 1.87 与 1.92 Date.parse

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5372464/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:43:37  来源:igfitidea点击:

Ruby 1.87 vs 1.92 Date.parse

ruby-on-railsruby

提问by mgm8870

In Ruby 1.87 I could do:

在 Ruby 1.87 中,我可以这样做:

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

Now in 1.9.2 I get:

现在在 1.9.2 我得到:

ArgumentError: invalid date

参数错误:无效日期

Any ideas?

有任何想法吗?

回答by Jon Gauthier

Use strptimeand give a specific time format.

使用strptime并给出特定的时间格式。

ruby-1.9.2-p136 :022 > Date.strptime '03/21/2011', '%m/%d/%Y'
 => #<Date: 2011-03-21 (4911283/2,0,2299161)>


See michaelmichael's responsefor the reason for this difference between Ruby versions.

有关Ruby 版本之间存在差异的原因,请参阅michaelmichael的回复

回答by michaelmichael

Per this bug report, the ability to parse mm/dd/yydates was intentionally removed in 1.9. Ruby's creator, Yukihiro Matsumoto says:

根据这个错误报告,解析mm/dd/yy日期的能力在 1.9 中被有意删除。Ruby 的创造者 Yukihiro Matsumoto 说:

"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.

“dd/dd/dd”格式本身非常依赖于文化并且模棱两可。日本(和其他国家)是 yy/mm/dd,美国是 mm/dd/yy,欧洲国家是 dd/mm/yy,对吧?在某些情况下,您可以偶然告诉他们,但在一般情况下,我们不应依靠运气。我相信这就是解析这种格式在 1.9 中被禁用的原因。

As hansengel suggests, you can use Date.strptimeinstead.

正如 hansengel 所建议的,您可以Date.strptime改用。

回答by John F. Miller

I have always had difficulty parsing dates with Date.parse. My solution is gratutious of the chronicgem. I also like the strptimefunction found in another answer.

我总是很难用Date.parse. 我的解决方案是免费的chronicgem。我也喜欢strptime在另一个答案中找到的功能。

回答by Tom Rossi

I like the american_dategem for accomplishing this...

我喜欢american_dategem 来完成这个......

回答by grosser

  class << self
    def parse_with_us_format(date, *args)
      if date =~ %r{^\d+/\d+/(\d+)$}
        Date.strptime date, "%m/%d/#{.length == 4 || args.first == false ? '%Y' : '%y'}"
      else
        parse_without_us_format(date, *args)
      end
    end
    alias_method_chain :parse, :us_format
  end