The application I'm working with insists on displaying all user-input dates (via jquery datepicker) in the non standard American %m/%d/%Y format. As a result we have a lot of strptime
methods scattered throughout our controllers.
I'm trying to clean it up and would like to overload the Rails to_date, to_datetime, and to_time extensions so these are no longer necessary.
#config/initializers/string.rb
class String
def to_date
begin
Date.strptime(self, '%m/%d/%Y') #attempt to parse in american format
rescue ArgumentError
Date.parse(self, false) unless blank? #if an error, execute original Rails to_date
#(pulled from Rails source)
end
end
def to_datetime
begin
DateTime.strptime(self,'%m/%d/%Y')
rescue ArgumentError
DateTime.parse(self, false) unless blank?
end
end
def to_time(form = :local)
begin
Time.strptime(self,'%m/%d/%Y')
rescue ArgumentError
parts = Date._parse(self, false)
return if parts.empty?
now = Time.now
time = Time.new(
parts.fetch(:year, now.year),
parts.fetch(:mon, now.month),
parts.fetch(:mday, now.day),
parts.fetch(:hour, 0),
parts.fetch(:min, 0),
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
parts.fetch(:offset, form == :utc ? 0 : nil)
)
form == :utc ? time.utc : time.getlocal
end
end
end
Anyway, this works great in rails console; "06/24/2014".to_date and variants behave exactly as I would like them. However, it looks like ActiveRecord doesn't use these overloaded definitions when creating/validating new table entries, eg
MyModelName.create(start_date:"06/07/2014")
gives a start date of 2014-07-06.
What can I do to make ActiveRecord recognize these overloaded definitions?
You can set default time and date formats in config/application.rb file this way:
my_date_formats = { :default => '%d.%m.%Y' }
Time::DATE_FORMATS.merge!(my_date_formats)
Date::DATE_FORMATS.merge!(my_date_formats)
The ruby-american_date gem may be what you want. It forces Date/DateTime/Time.parse to parse American formatted dates. Simply include it in your project's Gemfile.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.