How to check if a string is a valid date

后端 未结 15 1507
礼貌的吻别
礼貌的吻别 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 08:43

    A stricter solution

    It's easier to verify the correctness of a date if you specify the date format you expect. However, even then, Ruby is a bit too tolerant for my use case:

    Date.parse("Tue, 2017-01-17", "%a, %Y-%m-%d") # works
    Date.parse("Wed, 2017-01-17", "%a, %Y-%m-%d") # works - !?
    

    Clearly, at least one of these strings specifies the wrong weekday, but Ruby happily ignores that.

    Here's a method that doesn't; it validates that date.strftime(format) converts back to the same input string that it parsed with Date.strptime according to format.

    module StrictDateParsing
      # If given "Tue, 2017-01-17" and "%a, %Y-%m-%d", will return the parsed date.
      # If given "Wed, 2017-01-17" and "%a, %Y-%m-%d", will error because that's not
      # a Wednesday.
      def self.parse(input_string, format)
        date = Date.strptime(input_string, format)
        confirmation = date.strftime(format)
        if confirmation == input_string
          date
        else
          fail InvalidDate.new(
            "'#{input_string}' parsed as '#{format}' is inconsistent (eg, weekday doesn't match date)"
          )
        end
      end
    
      InvalidDate = Class.new(RuntimeError)
    end
    

提交回复
热议问题