Ruby日期格式验证

时间:2016-09-07 11:39:26

标签: ruby

我如何验证日期' 2016-01-01'格式正确(%Y-%m-%d)。

例如,如果日期格式正确,我想获得truefalse

伪代码:

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

请帮忙,

谢谢!

3 个答案:

答案 0 :(得分:5)

您似乎不仅对字符串的格式感兴趣,而且如果字符串表示有效日期(例如2016-01-32无效):

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"

或(将返回truefalse):

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

注意:Date.strptime会针对无效日期引发异常,因此rescue false会在这种情况下返回false

答案 1 :(得分:3)

由于问题的上下文没有严格规定,我将在Rails的上下文中添加一个可能的解决方案。我发现iso8601方法很有用,它会检查一个字符串是否是一个有效的iso8601日期,如果不是则会引发异常。 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

答案 2 :(得分:1)

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