Format date in rail model

I have a date of birth in a rail model, and I show it in different places. Every time I have to format it in mm/dd/yyyy format. Is there something that I can do in my model, so every time I get a dob, it comes in mm/dd/yyyy format.

+4
source share
2 answers

You can define a quick formatted_birthday method in your model, but if you just output it to representations, you can use the date formatting output built in the Rails format:

http://guides.rubyonrails.org/i18n.html#adding-date-time-formats

 # config/locales/en.yml en: time: formats: birthday: "%m/%d/%Y" 

Then, in your opinion, just use:

 <%= l person.birthday, :format => 'birthday' %> 

Or you can change birthday to default in the format definition, and you can omit the :format parameter all together.

+4
source

Yes, you can. In config / initializers / some_initializer.rb

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

Now all your dates will always be in the above format. If you want to selectively select it only occasionally. Then

 Date::DATE_FORMATS[:myformat] = "%m/%d/%Y" 

And then you can use whatever you like

 your_date.to_s(:myformat) 
+4
source

All Articles