user6801385 user6801385 - 3 months ago 28
Ruby Question

Ruby date format validation

How I can valid if date '2016-01-01' in the right format (%Y-%m-%d),

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

pseudo code:

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


Please help,

Thanks!

Answer

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 to return false in such a case.