ruby - 如何编写条件 : 'can this string be converted into a date type' ? (ruby)

标签 ruby date

我可以用 ruby​​ 编写这个条件吗?我需要知道字符串是否可以转换为日期变量。唯一的方法是 Date.parse("my string") 和异常。还有其他办法吗?

date_scraped_from_the_net = "20 Dec 2009" or it could be "today"

if date_scraped_from_the_net is not a date type 
  needs_to_be_updated = true
end

最佳答案

如果您需要复杂的日期解析,我会尝试 this .

但是,如果我理解您的具体问题,您将需要使用 rescue 来使用在条件中引发错误的方法:

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

关于ruby - 如何编写条件 : 'can this string be converted into a date type' ? (ruby),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2130542/

相关文章:

mysql - 在mysql中使用存储过程插入日期维度日期时出错

python - 在 Python 中解析人类格式的日期范围

ruby-on-rails - :to and => in rails有什么区别

swift - 从 UIDatepicker 获取日期组件

oracle - Oracle 中 SYS_EXTRACT_UTC() 的反函数是什么?

ruby - 使模块继承自 Ruby 中的另一个模块

javascript - 根据一个日期选择器的选定日期设置多个日期选择器的值

ruby - 是否可以在不递归的情况下创建 "SystemStackError: stack level too deep"错误?

ruby-on-rails - 检查模型上的关系表, rails 上的 ruby

ruby - 预期的带有扩展的 shell 命令可以在 Ruby 中工作(例如 `ls {Gemfile,Rakefile}` )