[ACCEPTED]-Ruby on Rails - how to display a date in format i need? Converting from YYYY-MM-DD HH:MM:SS UTC to MM/DD/YYYY-formatting

Accepted answer
Score: 33

In Rails you can use the to_time function on a 3 string to convert it into a Date object:

'2012-11-14 14:27:46'.to_time.strftime('%B %e at %l:%M %p')

#=> "November 14 at 2:27 PM"

For 2 a handy, interactive reference guide, refer 1 to http://www.foragoodstrftime.com/

Score: 27
Date.strptime(
  "2009-04-24 18:33:41 UTC",
  "%Y-%m-%d %H:%M:%S %Z"
).strftime("%m/%d/%Y")
# => "04/24/2009"

I think maybe you just got the capitalization 1 on your format strings wrong.

Score: 17

Check the active support documentation and 2 examples at: http://apidock.com/rails/ActiveSupport/CoreExtensions/DateTime/Conversions/to_formatted_s

Examples

datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0)   # => Tue, 04 Dec 2007 00:00:00 +0000

datetime.to_formatted_s(:db)            # => "2007-12-04 00:00:00"
datetime.to_s(:db)                      # => "2007-12-04 00:00:00"
datetime.to_s(:number)                  # => "20071204000000"
datetime.to_formatted_s(:short)         # => "04 Dec 00:00"
datetime.to_formatted_s(:long)          # => "December 04, 2007 00:00"
datetime.to_formatted_s(:long_ordinal)  # => "December 4th, 2007 00:00"
datetime.to_formatted_s(:rfc822)        # => "Tue, 04 Dec 2007 00:00:00 +0000"

Or if you really want 1 to customise it, define the helper like:

def custom_format(time)
  Time::DATE_FORMATS[:w3cdtf] = lambda { |time| time.strftime("%Y-%m-%dT%H:%M:%S# {time.formatted_offset}") }
end
Score: 3

You can use the String#to_time (or Date#to_time) function 3 in ActiveSupport to convert the string into 2 a Time (or Date) object. Then use strftime 1 as you have already.

Score: 3

Ive written a really nice gem that simplifies 2 the whole process, and makes date formatting 1 DRY.

Check it out at: http://github.com/platform45/easy_dates

Score: 1

What I have done is add an initializer named 5 conversions.rb in config/initializer After 4 that Add a line like follows:

ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.update(:<name> => '<formatting>')

From there 3 on you can render your datetime using your 2 format with:

dateVar.to_s(:<name>)

There is a handy list here of the 1 formatting tokens

Score: 0

Thanks a lot for the reply. My problem is, the 11 output seems to be already string and i 10 have to convert from date in string to another 9 format.

When I look at the date stored in 8 database (Oracle) it is mm/dd/yy, but when 7 i get it displayed, it adds the timestamp 6 and timezone.

I tried setting the default 5 in Configuration\environment.rb as ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!( :default 4 => '%d %b %Y' ) But that also doesn't 3 seem to help.

At the end, if I just get 2 the string to convert from Timezone format 1 to mm/dd/yyyy, that is enough.

More Related questions