如何验证日期“2016-01-01”的格式是否正确(%Y-%m-%d)。
例如我想得到true
or false
日期格式是否正确。
伪代码:
if ('2016-01-01' == (%Y-%m-%d))
puts date is valid
else
puts date is not valid
end
请帮忙,
Thanks!
由于没有严格指定问题的上下文,我将在 Rails 的上下文中添加一种可能的解决方案。我已经发现iso8601
方法很有用,它会检查字符串是否是有效的 iso8601 日期,如果不是,则会引发异常。http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html#method-i-iso8601 http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html#method-i-iso8601
def validate_date(date)
Date.iso8601(date.to_s)
return true
rescue ArgumentError
false
# although, in my case I felt that logging this error and raising exception was a better approach, since we are forwarding this to the user of our API.
# log_and_raise_error("Given argument is not a valid ISO8601 date: '#{date}'")
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)