user2993178 user2993178 - 5 months ago 8
Ruby Question

How can verify if a date is in the format dd mon ' yy in Ruby?

I have a column full of dates in the format dd mon 'yy (Ex: 20 Jan '16).
How can i verify that each date value in the column has this same format in Ruby?

Thanks

Answer

You can use Date.strptime which fails with an exception when it cannot parse the date:

require 'date'

Date.strptime("20 Jan '16", "%d %b '%y")
#=> <Date: 2016-01-20 ((2457408j,0s,0n),+0s,2299161j)>

Date.strptime("31 Feb '16", "%d %b '%y")
#=> ArgumentError: invalid date
Comments