Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime formatting in Ruby on Rails 4

I need to add this to my RoR 4 app to set default time, date and datetime formats. I followed this guide but I wasn't able to get it to work. I added it to the application.rb but dates would only change from 2014-05-27 07:05:00 UTC to 27/May/2014, and I want it to be 27/05/2014 5:00 PM.

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"              
like image 310
Frank004 Avatar asked May 26 '14 23:05

Frank004


3 Answers

I'm not sure why the article that you linked to differentiates between DateTime::DATE_FORMATS and Time::DATE_FORMATS. In my experience (and, apparently, in yours as well) Time::DATE_FORMATS speaks for Time as well as for 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 example output from 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"
like image 79
pdobb Avatar answered Oct 06 '22 00:10

pdobb


You should use the I18n helpers in combination with locales settings

I18n.localize(your_datetime_column, format: :short)

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

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

like image 28
house9 Avatar answered Oct 05 '22 23:10

house9


Without going through what the tutorial suggested, you can simply create a helper method and put it in your Helper folder. call that 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"
>> 
like image 29
Wally Ali Avatar answered Oct 05 '22 23:10

Wally Ali