Take the 2-minute tour ×

I'd like to accept date params without hyphens, such as 20110929. In Rails/Ruby, how can I convert this to a DateTime object? Do I need to edit the string manually, adding the appropriate hyphens, or is there some magic I'm not aware of?

Thanks guys!


Answered my own question, but unfortunately I can't accept it yet (low reputation):



As pointed out below, my above "answer" is probably not the best. See accepted answer below.

share|improve this question
Beware, plain .parse will try to "guess" the format, and might occasionally guess it incorrectly. –  Romain Sep 29 '11 at 15:03
So write your answer as a separate answer, and accept that one 24 hours later. You cannot accept your own answer immediately. –  mliebelt Sep 29 '11 at 15:04
@Romain If that's the case, then your answer is likely the better option. Thanks again! –  imderek Sep 29 '11 at 15:05
add comment

2 Answers

up vote 1 down vote accepted

In Ruby 1.9.2 you can use #strptime. In some cases, if the date format to parse is common, #parse should work as well.

require 'date'
require 'time'

DateTime.strptime("20110929", "%Y%m%d")
# => #<DateTime: 2011-09-29T00:00:00+00:00 (4911667/2,0/1,2299161)>
share|improve this answer
Thanks. You win by about a minute :-) –  imderek Sep 29 '11 at 15:16
add comment

You might want to use Date.strptime(params[:the_date], '%y%m%d'). See the apidock.

share|improve this answer
add comment

Your Answer


