开发者

Parsing a custom DATE_FORMAT with DateTime in Rails

How do I get DateTime to parse a custom date format(i.e. 'x-%Y')?

I've set the format within an initializer with (as per the RoR API):

Time::DATE_FORMATS[:x_year] = 'x-%Y'
Date::DATE_FORMATS[:x_year] = 'x-%Y'

and when I call:

DateTime.strptime('x-2011', 'x-%Y')

The correct result is returned, but

DateTime.parse('开发者_如何学Pythonx-2011')

Throws an

ArgumentError: invalid date


never heard of such a possibility. However, you could still do something like:

class DateTime
  class << self
    alias orig_parse parse
  end
  def self.parse(string, format = nil)
    return DateTime.orig_parse(string) unless format
    DateTime.strptime(string, Date::DATE_FORMATS[format])
  end
end

in your example it might look like that:

Date::DATE_FORMATS.merge!({:xform => "x-%Y"})
DateTime.parse('x-2011', :xform) #=> Sat, 01 Jan 2011 00:00:00 +0000

You could get rid of 'format' attribute and iterate && validate/rescue through DATE_FORMATS instead

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜