开发者

how to code a condition: 'can this string be converted into a date type'? (ruby)

开发者 https://www.devze.com 2022-12-18 11:43 出处:网络
can I code this condition in ruby somehow? I need to know if a string can be converted into a date variable. The only way how to do it is Date.parse(\"my string\") and exception. Is there any other wa

can I code this condition in ruby somehow? I need to know if a string can be converted into a date variable. The only way how to do it is Date.parse("my string") and exception. Is there any other way?

date_scraped_from_the_net = "20 Dec 2009"开发者_StackOverflow社区 or it could be "today"

if date_scraped_from_the_net is not a date type 
  needs_to_be_updated = true
end


If you need sophisticated date parsing, I would try this.

However, if I understand your specific question, you'll want to use rescue to use methods that raise errors in conditionals:

if (Date.parse(date_scraped_from_the_net) rescue nil)
  needs_to_be_updated = true
end
0

精彩评论

暂无评论...
验证码 换一张
取 消