user6801385
user6801385

Reputation:

Ruby date format validation

How I can verify that the date '2016-01-01' is in the right format (%Y-%m-%d).

For example I want to get true or false if the date is in the right format.

pseudo code:

if ('2016-01-01' == (%Y-%m-%d))
    puts date is valid
else
    puts date is not valid
end

Please help,

Thanks!

Upvotes: 5

Views: 13338

Answers (3)

spickermann
spickermann

Reputation: 106882

It seems like you are not only interested in the format of the string but also if the string represents a valid date (for example 2016-01-32 is invalid):

require 'date'

def validate_date(string)
  format_ok = string.match(/\d{4}-\d{2}-\d{2}/)
  parseable = Date.strptime(string, '%Y-%m-%d') rescue false

  if string == 'never' || format_ok && parseable
    puts "date is valid"
  else
    puts "date is not valid"
  end
end

validate_date('2016-01-01')
#=> "date is valid"

validate_date('2016-01-32')
#=> "date is not valid"

validate_date('01-01-2016')
#=> "date is not valid"

validate_date('never')
#=> "date is valid"

validate_date('today')
#=> "date is not valid"

Or (would return true or false):

require 'date'

def valid_date?(string)
  return true if string == 'never'

  !!(string.match(/\d{4}-\d{2}-\d{2}/) && Date.strptime(string, '%Y-%m-%d'))
rescue ArgumentError
  false
end

valid_date?('2016-01-01')
#=> true

valid_date?('2016-01-32')
#=> false

valid_date?('01-01-2016')
#=> false

valid_date?('never')
#=> true

valid_date?('today')
#=> false

Note: Date.strptime raises an exception for invalid dates, therefore the rescue false is required to return false in those a cases.

Upvotes: 7

bunufi
bunufi

Reputation: 764

Since the context of the question was not strictly specified I will add one possible solution in the context of Rails. I have found iso8601 method to be useful, which would check if a string is a valid iso8601 date and would raise exception if it is not. http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html#method-i-iso8601

def validate_date(date)
  Date.iso8601(date.to_s)
  return true
rescue ArgumentError
  false
  # although, in my case I felt that logging this error and raising exception was a better approach, since we are forwarding this to the user of our API.
  # log_and_raise_error("Given argument is not a valid ISO8601 date: '#{date}'")
end

Upvotes: 8

ShockwaveNN
ShockwaveNN

Reputation: 2268

require 'date'

def date_valid?(date)
  format = '%Y-%m-%d'
  DateTime.strptime(date, format)
  true
rescue ArgumentError
  false
end

p date_valid?('2016-01-01') # true
p date_valid?('2016-25-10') # false

Upvotes: 2

Related Questions