28

I need to parse a date string mentioned below into a Date object.

Is there a built in function in Ruby that would parse something like the string "December 09, 2011" to a Date of 2011-12-09?

Narfanator
  • 5,595
  • 3
  • 39
  • 71
user1810502
  • 531
  • 2
  • 7
  • 19

2 Answers2

40

Date.parse is already mentioned.

I prefer Date.strptime. This methods is a reverse strftime.

Date.parse is a (maybe good) guess, with Date.strptime you can parse each date, when you know which format you expect.

Example:

require 'date'
puts  Date.strptime('December 09, 2011', '%B %d, %Y')

Or if you have another format where Date.parse fails:

require 'date'
puts Date.strptime("28-May-10", "%d-%b-%y") #2010-05-28
Community
  • 1
  • 1
knut
  • 27,320
  • 6
  • 84
  • 112
20

Do as below using Date::parse:

require 'date'
Date.parse('December 09, 2011').to_s # => "2011-12-09"
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317