【问题标题】:Convert two-digit year to four-digit year in Ruby在 Ruby 中将两位数年份转换为四位数年份
【发布时间】:2010-12-11 00:15:46
【问题描述】:

我有 "84", "03" 等字符串,我想将其转换为 Date 对象,但 Date.new 仅将扩展的 4 位数年份作为参数。我知道这很简单,但我不想重新发明这个轮子。有什么东西已经这样做了吗?在标准 Ruby 或 ActiveSupport 中。

【问题讨论】:

    标签: ruby date time


    【解决方案1】:

    如果您想将 2 转换为 4 以供将来的日期使用(例如格式化信用卡到期日期),您可以尝试:

    $expYear  = 12
    
    if (strlen($expYear) == 2) {
        $expYear = substr(Date("Y"),0,2) . $expYear;
    }
    

    这将是更多的未来证明,因为它总是得到当前年份 但是,如果我们在本世纪 95 岁以上.. 它仍然会引起问题 我的人生

    【讨论】:

    • 您可以添加一个检查,看看结果年份是否过去,如果是,则转到下一个世纪(即卡片是否有效)
    【解决方案2】:

    大多数 2 位数的年份是过去的,所以一个好的截止值是 30。例如,如果有人输入 '66,他们很可能表示 1966。事实上,这也是 Excel 使用 2 时使用的截止值数字日期被传递到日期单元格。

    我有一个应用程序可以接受来自 excel 电子表格的制表符分隔文件,而且它们通常带有两位数的年份。我编写了这个 ActiveRecord 猴子补丁以允许 ActiveRecord 处理日期字段的两位数年份:

    class ActiveRecord::ConnectionAdapters::Column
      class << self
        protected
        # If a year comes in with two digits, let's try to guess whether it's in the
        # 20th or 21st century.  Typically, Ruby pivots this decision around the
        # year '69, but this is a bad guess.  Since most of our dates will arrive in
        # two digit format because of an Excel import, we should use the same pivot
        # value that Excel uses.  Excel pivots the decision around the year '30
        # which seems to be a better guess anyway.
        def new_date_with_two_digit_year_support(year, mon, mday)
          year += 2000 if (0..29).include? year
          year += 1900 if (30..99).include? year
          new_date_without_two_digit_year_support(year, mon, mday)
        end
        alias_method_chain :new_date, :two_digit_year_support
      end
    end
    

    这并不像问题所要求的那样通用,但希望它有所帮助。

    【讨论】:

      【解决方案3】:

      选择截止日期。

      if year < cutoff, then year4 = "20" + year
      else year4 = "19" + year
      

      另外,修复两位数年份的原因,否则您的系统将不符合 Y2K+cutoff 标准。

      【讨论】:

      • 是的,这就是我最终所做的。我只是想知道在某个库中是否有一些方便的方法。作为一个截止点,我使用了 70,因为 1970 年是 Unix 纪元 (en.wikipedia.org/wiki/Unix_time)。
      【解决方案4】:

      这样做真的有意义吗?什么时候应该停止考虑 19xx 日期?从年份的最后 2 位数字中得到 4 位数字的年份没有什么好方法。

      【讨论】:

      • 如果字符串代表生日,只是在表单上输入,而您并不关心 99 岁以上的人......是的。在某些情况下,它并不完全是疯狂的,我猜,但你想停下来说“我在这里解决了正确的问题吗?”
      • 这是一个特定于应用程序的问题。例如,如果您的应用程序只处理可追溯到 1980 年的记录,那么您可以将其用作截止日期。或者如果它只处理过去的数据,或者未来,或者......
      • 要求发生变化。这个问题的任何解决方案几乎肯定会在一年内打破。
      • ...或者至少在一百年内:-)
      【解决方案5】:

      我不知道这样的组件,也不知道你会怎么写;它如何决定使用哪个两位数前缀?盲目地选择一个有某些明显的问题。

      根据您的应用程序,您可能会找到一个合理的启发式方法,在 19 到 20 之间选择前缀,但问题通常无法解决;信息不足。

      【讨论】:

        猜你喜欢
        • 2011-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-27
        • 2016-05-26
        相关资源
        最近更新 更多