56

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

1

4 Answers 4

129

You could also use Date.strptime:

Date.strptime("{ 2009, 4, 15 }", "{ %Y, %m, %d }")
Sign up to request clarification or add additional context in comments.

2 Comments

What if the month is invalid... is there a method that return nil rather than raising an exception
@Ross: What's wrong with wrapping it in begin and rescue ArgumentError and in that case return nil?
6

Another way:

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

Comments

2
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

Comments

0

Another way:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.