BobBrez
BobBrez

Reputation: 723

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('x-2011')

Throws an

ArgumentError: invalid date

Upvotes: 2

Views: 1591

Answers (1)

Vlad Khomich
Vlad Khomich

Reputation: 5880

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

Upvotes: 2

Related Questions