Formatting DateTime in Ruby on Rails 4

I need to add this to my RoR 4 application to set the default time formats, date and date and time. I followed this guide, but I could not get it to work. I added it to application.rb, but the dates will only change from 2014-05-27 07:05:00 UTC to May 27/2014, and I want it to be 5/5/2014 05/27/2014.

http://blog.nicoschuele.com/posts/cheatsheet-to-set-app-wide-date-and-time-formats-in-rails

# Date # ---------------------------- Date::DATE_FORMATS[:default] = "%e/%B/%Y" # DateTime # ---------------------------- DateTime::DATE_FORMATS[:default] = "%m/%d/%Y %I:%M %p" # Time # ---------------------------- Time::DATE_FORMATS[:default] = "%e/%B/%Y" 
+7
ruby datetime ruby-on-rails
source share
3 answers

I'm not sure why the article you're linked to distinguishes between DateTime::DATE_FORMATS and Time::DATE_FORMATS . In my experience (and apparently in yours Time::DATE_FORMATS ) Time::DATE_FORMATS talks about time, as well as Date objects. So do this instead:

 # Date # ---------------------------- Date::DATE_FORMATS[:default] = "%e/%B/%Y" # DateTime / Time # ---------------------------- Time::DATE_FORMATS[:default] = "%m/%d/%Y %I:%M %p" 

Here is an example of the output of this in my console:

 > DateTime.current.to_s # => "05/27/2014 01:19 AM" > Time.current.to_s # => "05/27/2014 01:19 AM" > Date.current.to_s # => "27/May/2014" 
+11
source share

You must use the I18n in conjunction with the I18n settings.

 I18n.localize(your_datetime_column, format: :short) 

Then specify the formats in the locals file, i.e. config/locales/en.yml , you can change the existing short and long or add your own format keys. You may need to restart the rails after changing the locale files.

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

+6
source share

Without going through what the tutorial suggested, you can simply create a helper method and put it in your Helper folder. call this helper method in your views. Here is an example.

use the strftime method.

 def date_format(date) date.strftime("%d/%m/%Y %I:%M %p") end 

I tested it in irb .

 >> require 'date' => true >> d = DateTime.now => #<DateTime: 2014-05-26T18:54:59-05:00 ((2456804j,86099s,806097708n),-18000s,2299161j)> >> def date_format(date) >> date.strftime("%d/%m/%Y %I:%M %p") >> end => nil >> date_format(d) => "26/05/2014 06:54 PM" >> 
+4
source share

All Articles