Ruby: convert string to date

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

+54
string date ruby
Apr 27 2018-10-11T00:
source share
4 answers

You can also use Date.strptime :

 Date.strptime("{ 2009, 4, 15 }", "{ %Y, %m, %d }") 
+125
Apr 27 '10 at 12:12
source share

Another way:

 s = "{ 2009, 4, 15 }" d = Date.parse( s.gsub(/, */, '-') ) 
+6
Apr 27 '10 at 12:08 on
source share
 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 
+2
Apr 27 '10 at 12:17
source share

Another way:

 Date.new(*"{ 2009, 04, 15 }".scan(/\d+/).map(&:to_i)) 
0
Jan 17 '12 at 10:38
source share



All Articles