Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does 'Date.parse' not raise an exception for an invalid date string?

Tags:

date

ruby

I tried to create a method that returns a given string converted to date if the string is a valid date, else returns the string. This is the code:

def check_string(string)
  if date = (Date.parse(string) rescue nil)
    return date
  end
  string
end

When the string is:

"Análise de Novos Métodos Genéticos"

the Date.parse method returns a valid date:

#<Date: 2017-11-01 ((2458059j,0s,0n),+0s,2299161j)>

instead of raising an exception.

like image 894
Micael Avatar asked Dec 12 '25 07:12

Micael


1 Answers

Determining whether an arbitrary string corresponds to a valid date is extremely complicated. If possible, I would strongly suggest that you limit your application to only accept dates in a more restricted, well-defined format.

For example, you could use Date.strptime to test the string against specific format(s).

To understand what actually happened here, we can construct a minimal reproduction example:

Date.parse "Análise de Novos Métodos Genéticos"
#=> #<Date: 2017-11-01 ((2458059j,0s,0n),+0s,2299161j)>

Date.parse "Nov"
#=> #<Date: 2017-11-01 ((2458059j,0s,0n),+0s,2299161j)>

The library is interpreting this specific string to mean "1st November", because it contains "Nov".

like image 104
Tom Lord Avatar answered Dec 15 '25 03:12

Tom Lord



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!