【问题标题】:Differences in date string parsing between Ruby 1.9.3 and Ruby 1.8.7Ruby 1.9.3 和 Ruby 1.8.7 日期字符串解析的差异
【发布时间】:2012-02-28 14:18:02
【问题描述】:

使用 Ruby 1.8.7:

>> require 'time'
>> Time.parse '01/28/2012'
=> Sat Jan 28 00:00:00 +0200 2012
>> Time.parse '28/01/2012'
=> ArgumentError: argument out of range

使用 Ruby 1.9.3:

>> require 'time'
>> Time.parse '28/01/2012'
=> 2012-01-28 00:00:00 +0200
>> Time.parse '01/28/2012'
=> ArgumentError: argument out of range

看起来在 Ruby 1.8.7 中它接受美国格式(月/日/年),而在 Ruby 1.9.3 中它只接受非美国格式(日/月/年)。

有没有办法将此行为更改为像 Ruby 1.8.7 一样?

【问题讨论】:

    标签: ruby date time


    【解决方案1】:

    您是否可以使用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 
    

    【讨论】:

    • Ruby 只能很好地猜测日期格式,而美国格式由于模棱两可而令人愤怒。 01/02/03 是……究竟是什么? YY/MM/DD? DD/MM/YY? MM/DD/YY?
    • 因为有问题的代码使用的是 Rails 的String#to_time,它使用了Time.parse,所以我正在寻找一种解决方案来改变Time.parse 的工作方式。如果它不是现有代码,我肯定会使用Time.strptime——更强大。感谢您指出 ruby​​-american_date gem!
    【解决方案2】:

    Ruby 1.9.3 似乎更改了默认的日期解析格式...

    在 Ruby 1.8.7 中

    "11/14/2012".to_time
    ==> Wed Nov 14 00:00:00 UTC 2012
    

    在 Ruby 1.9.3 中

    "11/14/2012".to_time
    ArgumentError: invalid date
    

    to_time 转换现在接受 %d,%m,%Y 作为字符串格式...

    在 Ruby 1.9.3 中

    "14/11/2012".to_time
    2012-11-14 00:00:00 UTC
    

    注意输出的不同格式。 Time.now.to_s 在 1.9.3 中也返回不同的格式。小心!

    我看到另一个帖子说 to_time 在 Ruby 1.9.3 中被故意弃用,但似乎只有解析格式发生了变化。

    还有……

    在 1.8.7 中

    Time.parse("11/14/2012", "%m,%d,%Y")
    ==> Wed Nov 14 06:00:00 UTC 2012
    

    在 1.9.3 中

    Time.parse("11/13/2012", "%m,%d,%Y")
    ==> ArgumentError: argument out of range
    

    Time.strptime 在 1.8.7 中不存在,仅在 1.9.3 中存在,因此在对 1.9.3 进行必要的更改后,我看不到使我的代码向后兼容 1.8.7 的方法。

    【讨论】:

      猜你喜欢
      • 2014-02-18
      • 2012-07-21
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-28
      • 1970-01-01
      相关资源
      最近更新 更多