jjnevis
jjnevis

Reputation: 2870

Ruby: convert string to date

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

Upvotes: 56

Views: 64216

Answers (4)

Stalin
Stalin

Reputation: 164

Another way:

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

Upvotes: 0

FMc
FMc

Reputation: 42411

Another way:

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

Upvotes: 6

fl00r
fl00r

Reputation: 83680

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

Upvotes: 2

robinst
robinst

Reputation: 31417

You could also use Date.strptime:

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

Upvotes: 129

Related Questions