How to check if a string is a valid date

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

    Date.valid_date? *date_string.split('-').reverse.map(&:to_i)

    0 讨论(0)
  • 2020-12-02 08:46

    Posting this because it might be of use to someone later. No clue if this is a "good" way to do it or not, but it works for me and is extendible.

    class String
    
      def is_date?
      temp = self.gsub(/[-.\/]/, '')
      ['%m%d%Y','%m%d%y','%M%D%Y','%M%D%y'].each do |f|
      begin
        return true if Date.strptime(temp, f)
          rescue
           #do nothing
        end
      end
    
      return false
     end
    end
    

    This add-on for String class lets you specify your list of delimiters in line 4 and then your list of valid formats in line 5. Not rocket science, but makes it really easy to extend and lets you simply check a string like so:

    "test".is_date?
    "10-12-2010".is_date?
    params[:some_field].is_date?
    etc.
    
    0 讨论(0)
  • 2020-12-02 08:48

    Another way to validate date:

    date_hash = Date._parse(date.to_s)
    Date.valid_date?(date_hash[:year].to_i,
                     date_hash[:mon].to_i,
                     date_hash[:mday].to_i)
    
    0 讨论(0)
  • 2020-12-02 08:49
    require 'date'
    begin
       Date.parse("31-02-2010")
    rescue ArgumentError
       # handle invalid date
    end
    
    0 讨论(0)
  • 2020-12-02 08:49

    I'd like to extend Date class.

    class Date
      def self.parsable?(string)
        begin
          parse(string)
          true
        rescue ArgumentError
          false
        end
      end
    end
    

    example

    Date.parsable?("10-10-2010")
    # => true
    Date.parse("10-10-2010")
    # => Sun, 10 Oct 2010
    Date.parsable?("1")
    # => false
    Date.parse("1")
    # ArgumentError: invalid date from (pry):106:in `parse'
    
    0 讨论(0)
  • 2020-12-02 08:50

    Here is a simple one liner:

    DateTime.parse date rescue nil
    

    I probably wouldn't recommend doing exactly this in every situation in real life as you force the caller to check for nil, eg. particularly when formatting. If you return a default date|error it may be friendlier.

    0 讨论(0)
提交回复
热议问题