← Back to Upcase

Default Date Format


(Jarrett Green) #1

We have a couple of straight-up date fields in our app. When the form renders I’d like to to have the value to be in mm/dd/yy format. I’ve tried setting it up with i18n, and others, but I can’t find the right way to do it in Rails 3. Stack Overflow is all over the place with the ‘right’ way to do it.


(Derek Prior) #2

The best ‘right’ way to do it is to use localization to handle it. For instance

# config/locales/en.yml
en:
  date:
    formats:
      default: "%m-%d-%Y"

There’s similar settings for time. See the default rails i18n files

With this in place you’ll need to call localize(date_field) from your views. localize can be shortened to l if you would like, or you can wrap this in a helper method, say datestamp, in application_helper.rb if that suits you.


(Jarrett Green) #3

Gotcha, so in my form fields, I’ll still have to put a :value in there. I was hoping to get away from that part. I could write a helper to build it I guess, but it seems there should be another way.


(Chad Pytel) #4

@jarrettgreen If you’re using a form builder (formtastic or simple_form) you can override the date type, or make a new type which represents the date in the format you’d like.


(Jarrett Green) #5

Ahhhh. I AM using simple_form. Good idea, I’ll take a look.