How to check if a string is a valid date

后端 未结 15 1477
礼貌的吻别
礼貌的吻别 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条回答
  •  萌比男神i
    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.
    

提交回复
热议问题