129

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 true if the string is a valid date and false if it is not.

7
  • 2
    why not just make a date_time drop down instead of taking in a string that you have to validate?
    – corroded
    Commented Jun 2, 2010 at 7:51
  • client's requirement. i already suggest it but can't do that :)
    – Salil
    Commented Jun 2, 2010 at 8:06
  • As a general rule, aren't you supposed to do input validation on the front end of an application?
    – Seanny123
    Commented Jun 25, 2013 at 8:56
  • Much better answers here - this is how to do it. stackoverflow.com/questions/597328/…
    – n13
    Commented Nov 4, 2013 at 12:08
  • 8
    Always validate on the backend, no matter how good your front-end is, don't trust it!
    – SparK
    Commented Jan 28, 2016 at 18:53

17 Answers 17

124
require 'date'
begin
   Date.parse("31-02-2010")
rescue ArgumentError
   # handle invalid date
end
11
  • 30
    It's not a Date class feature, it's exception handling. Commented Aug 9, 2012 at 21:02
  • 4
    Date.parse('2012-08-13== 00:00:00') # => Mon, 13 Aug 2012
    – Bob
    Commented Aug 14, 2012 at 18:02
  • 14
    Using a "catch-it-all" rescue should be considered an anti-pattern. It can hide out other errors which we don't expect and make the debugging of the code extremely difficult.
    – yagooar
    Commented Jan 29, 2013 at 10:32
  • 9
    So... if it is indeed an anti-pattern, how would you answer the question? Commented Apr 12, 2013 at 4:35
  • 17
    Sorry this is a wrong answer. It doesn't check whether or not a string is a valid date, it merely checks of Date.parse can parse the string. Date.parse seems to be very forgiving when it comes to dates, e.g. it will parse "FOOBAR_09_2010" as the date 2012-09-09.
    – n13
    Commented Nov 4, 2013 at 12:00
61
d, m, y = date_string.split '-'
Date.valid_date? y.to_i, m.to_i, d.to_i
3
  • This is pretty simple and good for enforcing a xx-xx-YYYY format
    – n13
    Commented Nov 4, 2013 at 12:02
  • If you want to enforce a strict single format date string option, then this is the best option as it avoids Exceptions and is deterministic. Date.valid_date? is the method to use at least for Ruby 2. ruby-doc.org/stdlib-2.0.0/libdoc/date/rdoc/… Commented Nov 12, 2013 at 5:38
  • 4
    What version of Ruby supports is_valid?? Tried 1.8, 2.0 and 2.1. None of them seem to have that one. All seem to have valid_date?, though.
    – Henrik N
    Commented Jan 4, 2014 at 17:58
61

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.

3
  • 10
    DateTime.parse "123" rescue nil . This returns a real date.. May 3 2017
    – baash05
    Commented Apr 5, 2017 at 6:09
  • 4
    Date.strptime(date, '%d/%m/%Y') rescue nil Commented May 18, 2017 at 21:47
  • 2
    Use of inline rescue is discouraged.
    – smoyth
    Commented Apr 6, 2018 at 17:57
30

Parsing dates can run into some gotcha's, especially when they are in a MM/DD/YYYY or DD/MM/YYYY format, such as short dates used in U.S. or Europe.

Date#parse attempts to figure out which to use, but there are many days in a month throughout the year when ambiguity between the formats can cause parsing problems.

I'd recommend finding out what the LOCALE of the user is, then, based on that, you'll know how to parse intelligently using Date.strptime. The best way to find where a user is located is to ask them during sign-up, and then provide a setting in their preferences to change it. Assuming you can dig it out by some clever heuristic and not bother the user for that information, is prone to failure so just ask.

This is a test using Date.parse. I'm in the U.S.:

>> Date.parse('01/31/2001')
ArgumentError: invalid date

>> Date.parse('31/01/2001') #=> #<Date: 2001-01-31 (4903881/2,0,2299161)>

The first was the correct format for the U.S.: mm/dd/yyyy, but Date didn't like it. The second was correct for Europe, but if your customers are predominately U.S.-based, you'll get a lot of badly parsed dates.

Ruby's Date.strptime is used like:

>> Date.strptime('12/31/2001', '%m/%d/%Y') #=> #<Date: 2001-12-31 (4904549/2,0,2299161)>
6
  • Your LOCALE seems off. I get this >> Date.parse('01/31/2001') => Wed, 31 Jan 2001 >> ?> Date.parse('31/01/2001') ArgumentError: invalid date
    – hoyhoy
    Commented Aug 25, 2011 at 18:35
  • Not sure if I'm being daft here, but this seems to explain only how to parse a date, not how to validate it. The accepted answer uses the ArgumentError exception, but that doesn't seem like a good idea, for reasons noted in a comment there.
    – cesoid
    Commented Nov 6, 2014 at 20:43
  • There is a known situation where you can't validate a date. It's where the day and month values are ambiguous, and you have to know the format of the incoming date string. And, that is what the answer is saying. If it looks like 01/01/2014, which is the month and which is the day? In the US month would be first, the rest of the world it'd be second. Commented Nov 6, 2014 at 21:00
  • The ambiguity that prevents you from validating the date only does so to the extent that it also prevents you from parsing the date, but you've made a good attempt at parsing it with known information. It would be nice to use some of what you have to try to validate as best as we can. Can you think of how to do that without using exceptions that Date.parse and Date.strptime create?
    – cesoid
    Commented Aug 14, 2015 at 15:01
  • Date parsing in "mm/dd/yyyy" or "dd/mm/yyyy" format REQUIRES foreknowledge of the date's format. Without that we can't determine which it is unless we have a sampling from one source/user, then parse using both forms and then see which form generated the most exceptions and use the other. This breaks down when parsing dates from multiple sources, especially when they're global or they've been entered by hand. The only accurate way to deal with dates is to not allow hand-entry, to force users to use date-pickers, or only allow ISO date formats that are unambiguous. Commented Aug 14, 2015 at 16:12
29

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

3
  • Excellent, thanks. This one seems to be available at least in 1.8, 2.0 and 2.1. Note that you need to require "date" first or you'll get "undefined method".
    – Henrik N
    Commented Jan 4, 2014 at 17:59
  • 2
    This method can raise an exception 'ArgumentError: wrong number of arguments' instead of returning false. For example if your string contains slashes instead of dashes
    – vincentp
    Commented Jun 1, 2015 at 7:43
  • 2
    Maybe we can do something like this, for handling bad formatted date : Date.valid_date? *Array.new(3).zip(date_string.split('-')).transpose.last.reverse.map(&:to_i)
    – vincentp
    Commented Jun 1, 2015 at 8:25
11

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'
1
6

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)
1
  • 3
    Building on top of that, you can simplify this to: Date.valid_date?(*Date._parse(date).values)
    – Sunny
    Commented Oct 13, 2020 at 8:28
4

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
3
  • That's exactly what I was looking for. Thank you! Commented May 2, 2018 at 9:20
  • this fails for the cases like "2019-1-1" which is a valid date but the strftime makes it 2019-01-01
    – saGii
    Commented May 23, 2019 at 20:52
  • @saGii that doesn't fit the format specified (iso8601 - see Date.today().iso8601); %m is zero-padded. If you want something different, see ruby-doc.org/stdlib-2.4.0/libdoc/date/rdoc/… Commented May 24, 2019 at 17:19
3

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.
3

Try regex for all dates:

/(\d{1,2}[-\/]\d{1,2}[-\/]\d{4})|(\d{4}[-\/]\d{1,2}[-\/]\d{1,2})/.match("31-02-2010")

For only your format with leading zeroes, year last and dashes:

/(\d{2}-\d{2}-\d{4})/.match("31-02-2010")

the [-/] means either - or /, the forward slash must be escaped. You can test this on http://gskinner.com/RegExr/

add the following lines, they will all be highlighted if you use the first regex, without the first and last / (they are for use in ruby code).

2004-02-01
2004/02/01
01-02-2004
1-2-2004
2004-2-1
4
  • 2
    This regular expressions only match some fixed formats, without caring about the semantics of a date. Your matcher allows dates such as 32-13-2010 which is wrong.
    – yagooar
    Commented Oct 4, 2012 at 17:01
  • 2
    Good enough if you want a rough estimate if any arbitrary string could be parsed as a date. Commented Oct 17, 2013 at 13:49
  • Where "rough estimate" means values like '00/00/0000' and '99-99/9999' are possible candidates. Commented Aug 11, 2014 at 18:29
  • 1
    A brilliant example of when custom regex is a BAD IDEA!
    – Tom Lord
    Commented May 13, 2015 at 13:42
2

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
1

You can try the following, which is the simple way:

"31-02-2010".try(:to_date)

But you need to handle the exception.

0
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

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
1
  • Do you know why it returns the current date with that expression? what does "12!12*2012" mean? is it just bypassing the regular expression? Commented May 31, 2023 at 23:35
0

def validate_due_date
 flag = true
  while flag
  begin
    print "Enter a date (YYYY-MM-DD): "
    due_date = gets.chomp
    due_date = Date.parse(due_date)
    flag = false
  rescue => ex
    puts ex.message
  end
 end
 return due_date
end

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jan 30 at 14:43
0

date = "2024-02-30".to_date rescue nil, will save nil in date if it is not a valid date.

1
  • Note that comparing your post to existing posts (e.g. describing it as "simpler") will make it look weird when in the future other answers are added which are even simpler. Learn about formatting your code here: stackoverflow.com/help/formatting Otherwise thanks for contributing - and for explaining the core of your proposed solution. So few new users get the importance of that.
    – Yunnosch
    Commented Apr 29 at 11:58
-1

Method:

require 'date'
def is_date_valid?(d)
  Date.valid_date? *"#{Date.strptime(d,"%m/%d/%Y")}".split('-').map(&:to_i) rescue nil
end

Usage:

config[:dates].split(",").all? { |x| is_date_valid?(x)}

This returns true or false if config[:dates] = "12/10/2012,05/09/1520"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.