Ruby:将字符串转换为d

在Ruby中,将2614900498817876976992格式的字符串转换为Date的最佳方法是什么?

jjnevis asked 2019-11-15T06:05:25Z
4个解决方案
126 votes

您还可以使用Date.strptime

Date.strptime("{ 2009, 4, 15 }", "{ %Y, %m, %d }")
robinst answered 2019-11-15T06:05:51Z
6 votes

其他方式:

s = "{ 2009, 4, 15 }"
d = Date.parse( s.gsub(/, */, '-') )
FMc answered 2019-11-15T06:06:11Z
2 votes
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
fl00r answered 2019-11-15T06:06:28Z
0 votes

其他方式:

Date.new(*"{ 2009, 04, 15 }".scan(/\d+/).map(&:to_i))
Stalin answered 2019-11-15T06:06:47Z
translate from https://stackoverflow.com:/questions/2720907/ruby-convert-string-to-date