I have a birthday column in my csv that should allow user to input multiple date formats and then the file be imported via web page. At the moment the column is only set to one type of format; :birthday => (Date.strptime(row[2], "%mm/%dd/%YY") rescue nil),.
Is it possible to have multiple date formats?
Thanks!
2 Answers
Try Date.parse instead:
Parses the given representation of date and time, and creates a date object.
If the optional second argument is true and the detected year is in the range “00” to “99”, considers the year a 2-digit form and makes it full.
For example:
Date.parse('2001-02-03') #=> #<Date: 2001-02-03 ...> Date.parse('20010203') #=> #<Date: 2001-02-03 ...> Date.parse('3rd Feb 2001') #=> #<Date: 2001-02-03 ...>
If you need more control, you could always define your own parsing method.
2 Comments
Date.parse but it didn't work for me. Perhaps you can give me an example using my code from the question? Thanks.(Date.parse(row[2]) rescue nil) was sufficient.Rails' DateTime tries to detect the formatting automatically. It will detect the following formats: mm/dd/yy or dd-mm-yy or yyyy-mm-dd or yyyy/mm/dd.
Otherwise you'll have to build your own method that tries different parsing with the formats present on the file.