【发布时间】:2010-12-11 00:15:46
【问题描述】:
我有 "84", "03" 等字符串,我想将其转换为 Date 对象,但 Date.new 仅将扩展的 4 位数年份作为参数。我知道这很简单,但我不想重新发明这个轮子。有什么东西已经这样做了吗?在标准 Ruby 或 ActiveSupport 中。
【问题讨论】:
我有 "84", "03" 等字符串,我想将其转换为 Date 对象,但 Date.new 仅将扩展的 4 位数年份作为参数。我知道这很简单,但我不想重新发明这个轮子。有什么东西已经这样做了吗?在标准 Ruby 或 ActiveSupport 中。
【问题讨论】:
如果您想将 2 转换为 4 以供将来的日期使用(例如格式化信用卡到期日期),您可以尝试:
$expYear = 12
if (strlen($expYear) == 2) {
$expYear = substr(Date("Y"),0,2) . $expYear;
}
这将是更多的未来证明,因为它总是得到当前年份 但是,如果我们在本世纪 95 岁以上.. 它仍然会引起问题 我的人生
【讨论】:
大多数 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
这并不像问题所要求的那样通用,但希望它有所帮助。
【讨论】:
选择截止日期。
if year < cutoff, then year4 = "20" + year
else year4 = "19" + year
另外,修复两位数年份的原因,否则您的系统将不符合 Y2K+cutoff 标准。
【讨论】:
这样做真的有意义吗?什么时候应该停止考虑 19xx 日期?从年份的最后 2 位数字中得到 4 位数字的年份没有什么好方法。
【讨论】:
我不知道这样的组件,也不知道你会怎么写;它如何决定使用哪个两位数前缀?盲目地选择一个有某些明显的问题。
根据您的应用程序,您可能会找到一个合理的启发式方法,在 19 到 20 之间选择前缀,但问题通常无法解决;信息不足。
【讨论】: