format a date in the rails model
I have a date of birth in the rails model and I display it in different places. Every time I have to specifica开发者_开发问答lly format it in mm/dd/yyyy
format. Is there something I can do in my model so that every time I get the dob out it comes in mm/dd/yyyy
format.
You can define a quick formatted_birthday
method in your model, but if you're just outputting this to views you can use Rails' built in date formatting output:
http://guides.rubyonrails.org/i18n.html#adding-date-time-formats
# config/locales/en.yml
en:
time:
formats:
birthday: "%m/%d/%Y"
Then in your view just use:
<%= l person.birthday, :format => 'birthday' %>
Or you can change birthday
to default
in the format definition and you can omit the :format
option all together.
Yes you can. In config/initializers/some_initializer.rb
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
Now all your dates will always be out in the above format. If you want to selectively choose it only sometimes. Then
Date::DATE_FORMATS[:myformat] = "%m/%d/%Y"
And then you can use whereever you like
your_date.to_s(:myformat)
精彩评论