I needed to show date in localized format. i.e. 12/31/2013
Therefore, I set the default date format to that format in config/initializers/datetime_formats.rb
Date::DATE_FORMATS[:default]="%m/%d/%Y"
Time::DATE_FORMATS[:default]="%m/%d/%Y %H:%M"
However, my tests failed in unit tests because some searches are based on date format. For example
>> User.find_by_created_at("#{DateTime.now}")
User Load (2.7ms) SELECT `users`.* FROM `users`
WHERE `users`.`created_at` = '02/04/2013 14:43' LIMIT 1
Of course, I can change all models to use all date or datetime search to use Date class or DateTime class instead of string. But, I got curious if we can apply view-only date format or view-only time format or not.
Is there a way to apply view-only date(or time) format?
----- edit -----
I already have custom method l_or_none for views with exception handling.
def l_or_none(object)
l(object) rescue ''
end
I just don't want to repeat this method all over the views, and looking for a way, "if Date#to_s is called in view, format this way", without using my own method.
Why don't we have a concept like this?
"If this object is used under view, override method in this way"
You could use the localization of rails:
config/locales/en-US.yml
date:
formats:
default: "%m/%d/%Y"
short: "%m/%d"
datetime:
formats:
default: "%m/%d/%Y %H:%M"
short: "%H:%M"
notime: "%m/%d/%Y"
And in the view:
<%= l(@entry.created_at) %>
<%= l(@entry.created_at, :format => :short) %>
<%= l(@entry.created_at, :format => :notime) %>
result:
02/13/2013 15:24
15:24
02/13/2013
http://guides.rubyonrails.org/i18n.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With