简体   繁体   中英

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

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, ie 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?

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 eg

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM