Ruby 1.87 vs 1.92 Date.parse

前端 未结 5 2001
甜味超标
甜味超标 2021-02-01 12:56

In Ruby 1.87 I could do:

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

Now in 1.9.2 I get:

ArgumentError: invalid date

<
相关标签:
5条回答
  • 2021-02-01 13:33

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

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

    As hansengel suggests, you can use Date.strptime instead.

    0 讨论(0)
  • 2021-02-01 13:33

    I like the american_date gem for accomplishing this...

    0 讨论(0)
  • 2021-02-01 13:48

    I have always had difficulty parsing dates with Date.parse. My solution is gratutious of the chronic gem. I also like the strptime function found in another answer.

    0 讨论(0)
  • 2021-02-01 13:48
      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
    
    0 讨论(0)
  • 2021-02-01 13:50

    Use strptime and give a specific time format.

    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 response for the reason for this difference between Ruby versions.

    0 讨论(0)
提交回复
热议问题