Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is : Date.parse("123 456 789") == Fri, 03 May 2019?

Tags:

ruby

The title pretty much says it all. I'm trying to assess the validity of dates from a CSV import but if someone chooses a telephone number column for date of birth the Date parsing still passes

like image 427
Mark Kenny Avatar asked Dec 24 '22 00:12

Mark Kenny


2 Answers

How is : Date.parse(“123 456 789”) == Fri, 03 May 2019?

Date._parse (with an underscore) returns the raw data:

Date._parse('123 456 789')
#=> {:yday=>123}

Ruby treats 123 as the day of the year and the 123rd day of the current year is May 3.

like image 106
Stefan Avatar answered Jan 05 '23 02:01

Stefan


The documentation on Date#parse explicitly states:

This method does not function as a validator.

That means, this method is omnivorous, it’ll produce a date from whatever input. You need to use Date#iso8601 instead:

main > Date.iso8601("2019-03-19")
#⇒ #<Date: 2019-03-19 ((2458562j,0s,0n),+0s,2299161j)>
main > Date.iso8601("123 456 789")
#⇒ ArgumentError: invalid date
like image 30
Aleksei Matiushkin Avatar answered Jan 05 '23 01:01

Aleksei Matiushkin