开发者

format a date in the rails model

开发者 https://www.devze.com 2023-03-03 18:53 出处:网络
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 s

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号