How to check if a string is a valid date

后端 未结 15 1510
礼貌的吻别
礼貌的吻别 2020-12-02 08:09

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

I need a method which which returns

15条回答
  •  被撕碎了的回忆
    2020-12-02 09:01

    Similar to the solution by @ironsand, I prefer to create an overridden instance method on String:

    class String
      def valid_datetime?
        to_datetime
        true
      rescue ArgumentError
        false
      end
    end
    

提交回复
热议问题