我在美国,我们通常把日期安排为“月/日/年”。我正在努力确保我的Rails应用程序(使用Ruby1.9)在任何地方都采用这种格式,并且在Ruby1.8下的工作方式是一样的。
我知道很多人都有这个问题,所以我想在这里创建一个明确的指南。
具体地说:
,我该怎么做?
到目前为止我的情况是这样的。
控制Date#to_s行为
我在application.rb里有这一行
# Format our dates like "12/25/2011'
Date::DATE_FORMATS[:default] = '%m/%d/%Y'这确保了如果我这样做的话:
d = Date.new(2011,4,1)
d.to_s..。我得到"04/01/2011",而不是"2011-04-01“。
控制String#to_date行为
ActiveSupport的String#to_date方法目前看起来如下(来源):
def to_date
return nil if self.blank?
::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
end(如果您不这样做,第二行将创建一个新的日期,按该顺序按年、月和日传递。获取年份、月和日值的方法是使用Date._parse,它解析一个字符串并以某种方式决定这些值是什么,然后返回一个散列。.values_at按Date.new想要的顺序从哈希中提取值。)
因为我知道我通常会传递像"04/01/2011“或"4/1/2011”这样的字符串,所以我可以这样通过猴子来修正这个问题:
class String
# Keep a pointer to ActiveSupport's String#to_date
alias_method :old_to_date, :to_date
# Redefine it as follows
def to_date
return nil if self.blank?
begin
# Start by assuming the values are in this order, separated by /
month, day, year = self.split('/').map(&:to_i)
::Date.new(year, month, day)
rescue
# If this fails - like for "April 4, 2011" - fall back to original behavior
begin
old_to_date
rescue NoMethodError => e
# Stupid, unhelpful error from the bowels of Ruby date-parsing code
if e.message == "undefined method `<' for nil:NilClass"
raise InvalidDateError.new("#{self} is not a valid date")
else
raise e
end
end
end
end
end
class InvalidDateError < StandardError; end;这个解决方案能让我的测试通过,但它疯了吗?我只是在某个地方遗漏了一个配置选项,还是有其他更简单的解决方案?
还有其他我没有报道的日期解析案例吗?
发布于 2012-01-03 13:45:58
发布于 2011-09-12 20:57:09
Date.strptime可能是您在ruby1.9中要找的东西。
现在您可能已经将它卡在string.to_date上了,但是strptime是从ruby1.9中解析字符串日期的最佳解决方案。
此外,据我所知,格式与strftime是对称的。
发布于 2011-09-14 03:40:22
您可以使用rails-i18n宝石或复制en-US.yml,并在config/application.rb中设置默认的"en-US"
https://stackoverflow.com/questions/7286467
复制相似问题