且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查字符串是否是有效的日期。 Ruby on Rails

更新时间:2022-10-15 10:32:08

  require'date'
begin
Date.parse(31-02-2010)
rescue ArgumentError
#handle invalid date
end


Say I have a string: "31-02-2010" and I want to check see whether or not it is a valid date or not. What is the best way to do it?

I need a method which I can call on string which returns true if the string is a valid date and false if it is not.

require 'date'
begin
   Date.parse("31-02-2010")
rescue ArgumentError
   # handle invalid date
end