Ruby: convert string to date

RubyStringDate

Ruby Problem Overview


In Ruby, what's the best way to convert a string of the format: "{ 2009, 4, 15 }" to a Date?

Ruby Solutions


Solution 1 - Ruby

You could also use Date.strptime:

Date.strptime("{ 2009, 4, 15 }", "{ %Y, %m, %d }")

Solution 2 - Ruby

Another way:

s = "{ 2009, 4, 15 }"
d = Date.parse( s.gsub(/, */, '-') )

Solution 3 - Ruby

def parse_date(date)
  Date.parse date.gsub(/[{}\s]/, "").gsub(",", ".")
end

date = parse_date("{ 2009, 4, 15 }")
date.day
#=> 15
date.month
#=> 4
date.year
#=> 2009

Solution 4 - Ruby

Another way:

Date.new(*"{ 2009, 04, 15 }".scan(/\d+/).map(&:to_i))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjjnevisView Question on Stackoverflow
Solution 1 - RubyrobinstView Answer on Stackoverflow
Solution 2 - RubyFMcView Answer on Stackoverflow
Solution 3 - Rubyfl00rView Answer on Stackoverflow
Solution 4 - RubyStalinView Answer on Stackoverflow