I was looking for a way to change the default date format in Rails 4.
Asked
Active
Viewed 2.4k times
3 Answers
50
Found a nice approach through the Rails Internationalization (I18n) API
Data and time formats can be 'translated' by adding the format to the i18n configuration.
config/locales/en.yml
en:
date:
formats:
default: "%d/%m/%Y"
time:
formats:
default: "%d/%m/%Y %H:%M"
Note: remember to not have tabs for the indent, like I did first time :)
As mentioned by NoelProf in the comments
To use i18n conversion don't forget the l (lower case L) before your date in views! For example: <%= l your_date %>
You are invited to comment if you found other ways working well.
-
awesome.. saved me some time :) – whizcreed Nov 03 '14 at 19:14
-
5To use i18n conversion don't forget the l (lower case L) before your date in views! For example: `<%= l your_date %>` – NoelProf Jan 28 '16 at 05:22
33
Add this
# Date
Date::DATE_FORMATS[:default] = "%d/%m/%Y"
# Time
Time::DATE_FORMATS[:default] = "%d/%m/%Y %H:%M"
to config/initializers/date_time.rb
Then restart the server.
-
3Is it typical to use `date_time.rb` as the file name? I know it doesn't matter but in the code example from http://api.rubyonrails.org/classes/DateTime.html#method-i-to_formatted_s it shows `time_format.rb`. – Kirk Jun 30 '16 at 18:43
3
If you use i18n conversion don't forget the l
method before your dates in views!
<%= l your_date %>

NoelProf
- 865
- 7
- 7

Markus Andreas
- 935
- 1
- 13
- 12
-
Welcome to StackOverflow, please edit your answer to make it for the questioner better to understand your solution. – Leonid Glanz Oct 01 '15 at 12:32