鉴于3个数字:DD,MM,YYYY,知道他们是否结合法定日期的最简单方法是什么?
示例:
14, 05, 2011 => Legal
29, 02, 2011 => Illegal
29, 02, 2012 => Legal
35, 11, 1989 => Illegal
14, 18, 2011 => Illegal
14, 00, 2011 => Illegal
00, 11, 1979 => Illegal
31, 11, 1979 => Illegal
答案 0 :(得分:11)
您可以使用valid_date?
但它是YYYY, MM, DD
:
irb(main):015:0> require 'date'
=> true
irb(main):021:0> Date::valid_date?(2011,05,14)
=> true
irb(main):022:0> Date::valid_date?(2011,02,29)
=> false
irb(main):023:0> Date::valid_date?(2012,02,29)
=> true
答案 1 :(得分:4)
日期有一个方法valid_civil?
require 'date'
dates = DATA.readlines.map{|line| line.split(', ').map(&:to_i)}
dates.each do |date|
d, m, y = date
puts Date.valid_civil?(y, m, d)
end
__END__
14, 05, 2011
29, 02, 2011
29, 02, 2012
35, 11, 1989
14, 18, 2011
14, 00, 2011
00, 11, 1979
31, 11, 1979
答案 2 :(得分:0)
一种选择是使用类似的东西:
require 'time'
def valid(year,month,day)
Time.parse "#{year}#{month}#{day}" rescue return false
return true
end