How to check if a string is a valid date

后端 未结 15 1318
礼貌的吻别
礼貌的吻别 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:58

    Date.parse not raised exception for this examples:

    Date.parse("12!12*2012")
    => Thu, 12 Apr 2018
    
    Date.parse("12!12&2012")
    => Thu, 12 Apr 2018
    

    I prefer this solution:

    Date.parse("12!12*2012".gsub(/[^\d,\.,\-]/, ''))
    => ArgumentError: invalid date
    
    Date.parse("12-12-2012".gsub(/[^\d,\.,\-]/, ''))
    => Wed, 12 Dec 2012
    
    Date.parse("12.12.2012".gsub(/[^\d,\.,\-]/, ''))
    => Wed, 12 Dec 2012
    
    0 讨论(0)
  • 2020-12-02 08:59
    require 'date'
    #new_date and old_date should be String
    # Note we need a ()
    def time_between(new_date, old_date)
      new_date = (Date.parse new_date rescue nil)
      old_date = (Date.parse old_date rescue nil)
      return nil if new_date.nil? || old_date.nil?
      (new_date - old_date).to_i
    end
    
    puts time_between(1,2).nil?
    #=> true
    puts time_between(Time.now.to_s,Time.now.to_s).nil?
    #=> false
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题