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
In Rails you can use the to_time
function on a 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 a handy, interactive reference guide, refer to http://www.foragoodstrftime.com/
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 on your format strings wrong.
Check the active support documentation and 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 +0000datetime.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 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