7.10. Validating a Date/Time

As we saw in section 7.5 “Finding the Nth Weekday in a Month,” the standard date/time functions do not check the validity of a date, but “roll it over” as needed. For example, November 31 is translated to December 1.

At times, this may be the behavior you want. If it is not, you will be happy to know that the standard library Date does not regard such a date as valid. We can use this fact to perform validation of a date as we instantiate it.

class Time def Time.validate(year, month=1, day=1, hour=0, min=0, sec=0, usec=0) require "date" begin d = Date.new(year,month,day) rescue return nil end Time.local(year,month,day,hour,min,sec,usec) end end t1 = Time.validate(2000,11,30) # Instantiates a valid object t2 = Time.validate(2000,11,31) ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.