Convert string to a specific date and time format?

Line

"2011-05-19 10:30:14" 

To

 Thu May 19 10:30:14 UTC 2011 

How to convert a specific string to this date format?

+48
ruby ruby-on-rails
May 20 '11 at 11:01
source share
7 answers
 require 'date' date = DateTime.parse("2011-05-19 10:30:14") formatted_date = date.strftime('%a %b %d %H:%M:%S %Z %Y') 

See strftime () for more information on formatting dates.

+104
May 20 '11 at 11:13
source share

"2011-05-19 10:30:14".to_time

+31
May 20 '11 at 11:04
source share

There is no need to apply anything. Just add this code at the end of the variable to which the date is assigned. for example

  @todaydate = "2011-05-19 10:30:14" @todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y') 

You will receive the correct format as you wish. You can check it in the Rails console

 Loading development environment (Rails 3.0.4) ruby-1.9.2-p136 :001 > todaytime = "2011-05-19 10:30:14" => "2011-05-19 10:30:14" ruby-1.9.2-p136 :002 > todaytime => "2011-05-19 10:30:14" ruby-1.9.2-p136 :003 > todaytime.to_time => 2011-05-19 10:30:14 UTC ruby-1.9.2-p136 :008 > todaytime.to_time.strftime('%a %b %d %H:%M:%S %Z %Y') => "Thu May 19 10:30:14 UTC 2011" 

Try "date_format" to display the date in a different format.

All the best!!!

+13
May 20 '11 at 11:25
source share

Other formats:

  require 'date' date = "01/07/2016 09:17AM" DateTime.parse(date).strftime("%A, %b %d") #=> Friday, Jul 01 DateTime.parse(date).strftime("%m/%d/%Y") #=> 07/01/2016 DateTime.parse(date).strftime("%m-%e-%y %H:%M") #=> 07- 1-16 09:17 DateTime.parse(date).strftime("%b %e") #=> Jul 1 DateTime.parse(date).strftime("%l:%M %p") #=> 9:17 AM DateTime.parse(date).strftime("%B %Y") #=> July 2016 DateTime.parse(date).strftime("%b %d, %Y") #=> Jul 01, 2016 DateTime.parse(date).strftime("%a, %e %b %Y %H:%M:%S %z") #=> Fri, 1 Jul 2016 09:17:00 +0200 DateTime.parse(date).strftime("%Y-%m-%dT%l:%M:%S%z") #=> 2016-07-01T 9:17:00+0200 DateTime.parse(date).strftime("%I:%M:%S %p") #=> 09:17:00 AM DateTime.parse(date).strftime("%H:%M:%S") #=> 09:17:00 DateTime.parse(date).strftime("%e %b %Y %H:%M:%S%p") #=> 1 Jul 2016 09:17:00AM DateTime.parse(date).strftime("%d.%m.%y") #=> 01.07.16 DateTime.parse(date).strftime("%A, %d %b %Y %l:%M %p") #=> Friday, 01 Jul 2016 9:17 AM 
+8
Jan 07 '16 at 9:59 on
source share

Use DATE_FORMAT from Date Conversion :

In your initializer:

 DateTime::DATE_FORMATS[:my_date_format] = "%a %b %d %H:%M:%S %Z %Y" 

In your opinion:

 date = DateTime.parse("2011-05-19 10:30:14") date.to_formatted_s(:my_date_format) date.to_s(:my_date_format) 
+3
May 20 '11 at 11:38
source share

This is another useful code:

 "2011-05-19 10:30:14".to_datetime.strftime('%a %b %d %H:%M:%S %Z %Y') 
+3
Aug 20 '14 at 0:11
source share
  <%= string_to_datetime("2011-05-19 10:30:14") %> def string_to_datetime(string,format="%Y-%m-%d %H:%M:%S") DateTime.strptime(string, format).to_time unless string.blank? end 
+1
May 20 '11 at 12:07
source share



All Articles