Ruby - convert string to date

I have a line like "2011-06-02T23: 59: 59 + 05: 30".

I want to convert it to a date format and parse only the date, "2011-06-02".

+8
date ruby
source share
4 answers

For Ruby 1.9.2:

require 'date' # If not already required. If in Rails then you don't need this line). puts DateTime.parse("2011-06-02T23:59:59+05:30").to_date.to_s 
+24
source share
 require 'date' d = Date.parse("2011-06-02T23:59:59+05:30") d.strftime("%F") 
+12
source share

Simplification:

 require 'date' date = "2011-06-02T23:59:59+05:30".gsub(/T.*/, '') DateTime.parse(date) 
+2
source share

Time.parse () should allow you to analyze the time of the entire date. Then you can use time.strftime (string) to format it as a date in a string.

 date = Time.parse ("2011-06-02T23: 59: 59 + 05: 30")
 date_string = time.strftime ("% y-% m-% d")
 of
 date_string = time.strftime ("% F")

(see Ruby Doc for Time for more output string formats) The above should work if you want a string; if you want a date object to be processed, the Ruby Date class can help you deal with this, but I believe that you still need to do with Time objects; see Ruby Doc for Date for details on the Date class.

Hope this helps, let me know if I answer in the wrong direction with my answer.

+2
source share

All Articles