如何识别给定的日、月、年是否合并了一个法定日期



给定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

你可以用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

Date有一个方法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

其中一个选项是:

require 'time'
def valid(year,month,day)
   Time.parse "#{year}#{month}#{day}" rescue return false
   return true
end

相关内容

  • 没有找到相关文章

最新更新