Home > Enterprise >  Ruby 'strptime()' not raising ArgumentError when passing invalid date format'
Ruby 'strptime()' not raising ArgumentError when passing invalid date format'

Time:01-27

I could use some help with an issue I am facing in a Rails project. I am using the strptime function to return a Date object from an inputted string time and target format:

date = Date.strptime(date, '%Y-%m')

And it seems when I pass in a Date that doesn't match that pattern, i.e. 01-01-24, it does not throw an ArgumentError for me to catch and do anything with. It does catch an invalid input like this: 01-2024 though. Is there a certain kind of validation I can do here to catch this kind of error and check that the RegEx pattern matches?

CodePudding user response:

Date#strptime format is using '%Y-%m' as [year]-[month] so in the case of '01-01-2024' it is seen as [01]-[01]-2024 and parsed to that date structure.

strptime does not respect %Y as having a minimum width so your current expression is essentially equivalent to /\A-?\d -(?:1[0-2]|0?[1-9])/ (any number of digits followed by a hyphen followed by 1-12 optionally 0 padded)

'01-2024' only raises an error because 20 is not a valid month. For Example: '01-1299' would not raise an error.

Rather than relying on this naivety, you could validate your "date pattern" using a Regexp e.g.

date.match?(/\A\d{4}-(?:1[0-2]|0[1-9])\z/)

CodePudding user response:

Using pry to investigate with:

[22] pry(main)> date = Date.strptime('calimero', '%Y-%m')
Date::Error: invalid date
from (pry):20:in `strptime'

it throws a Date::Error exception

  • Related