1

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!

0

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I've tried Date.parse but it didn't work for me. Perhaps you can give me an example using my code from the question? Thanks.
Actually, Date.parse worked perfectly, I just didn't write it correctly the first time. So, doing this, (Date.parse(row[2]) rescue nil) was sufficient.
0

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.

1 Comment

Thanks. I am aware of the Rails formats, what I really need is a way of implementing all of those three formats into one method or whatever that maybe. This brings me to a case statement that could check on a format and then parse the date into a table, but I haven't tried this yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.