Rails 3, date only format?

I needed to show the date in a localized format. those. 12/31/2013

Therefore, I set the default date format for this format to config / initializers / datetime_formats.rb

Date::DATE_FORMATS[:default]="%m/%d/%Y" Time::DATE_FORMATS[:default]="%m/%d/%Y %H:%M" 

However, my tests did not run in unit tests, because some searches are based on date format. for instance

 >> 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 the entire search by date or date, to use the Date or DateTime class instead of the string. But I was curious if we can use the date format for viewing only or the format of the viewing time or not.

Is there a way to apply the date (or time) format for viewing only?

----- edit -----

I already have a custom l_or_none method for views with exception handling.

 def l_or_none(object) l(object) rescue '' end 

I just don’t want to repeat this method across all views and look for a way: "if Date # to_s is called in the view, format this way" without using my own method.

Why don't we have such a concept?

"If this object is used in view mode, override the method this way"

+6
source share
2 answers

You can use rail localization:

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

+18
source

Try this, and maybe everything will be fine:

 User.find_by_created_at(DateTime.now) 
0
source

All Articles