Skip to content

Instantly share code, notes, and snippets.

@varnie
Created September 7, 2011 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save varnie/1200030 to your computer and use it in GitHub Desktop.
Save varnie/1200030 to your computer and use it in GitHub Desktop.
A function checking the date is valid
=begin rdoc
Checks that the supplied date has the correct date format '#YYYY:MM:DD' with the separators both be either - or : or /.
A year cannot start from the zero, while a month and a day can.
Performs additional checkings that the date is valid.
=end
def checkDateUpdated(aDate)
matched =
%r{
(?<year>
(^ #no input before the start
[1-9]\d{3} #a year cannot start from the zero
)
)
(?<sep>-|:|/) #a separator can be either - or : or /
(?<month>
(0[1-9]) #a month can start from the zero
|
(1[0-2]) #or it could be just 10, 11 or 12 of course
)
\k<sep> #the 2nd separator must be the same as the 1st met
(?<day>
(0[1-9]) #a day can start from the zero
|(1[0-9]) #or should fall into the range [1..31]
|(2[0-9])
|30
|31
)$ #marks there should be the end of the input
}x.match(aDate)
if (matched)
day, month, year = matched[:day], matched[:month], matched[:year]
day = day[-1] if day[0] == "0"
month = month[-1] if month[0] == "0"
year, month, day = year.to_i, month.to_i, day.to_i
require 'date'
begin
date = Date.new(year, month, day)
rescue ArgumentError => e
return false
end
true
else
false
end
end
date = "2011:11:30"
print "date is #{checkDateUpdated(date) ? "" : "not "}correct"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment