Search code examples
rubydatetimestrptime

Can't get Ruby strptime to work


I currently have

format = '%d%m%Y:%H:%M:%S'
date_time = '30/Jun/2013:07:38:27'

puts DateTime.strptime(date_time, format)

which returns

ArgumentError: invalid date
    from (irb):95:in 'strptime'
    from (irb):97
    from (irb):usr/bin/irb:12:in '<main>'

How can I make this work?

Thanks!


Solution

  • Your format string doesn't match the format you're actually using. %m is the zero-padded month (01..12), whereas you're using Jun, which calls for %b. You also need to put slashes in to make the format match.

    This is all documented.

    require 'date'
    
    format = '%d/%b/%Y:%H:%M:%S'
    date_time = '30/Jun/2013:07:38:27'
    DateTime.strptime(date_time, format)
    # => #<DateTime: 2013-06-30T07:38:27+00:00 ((2456474j,27507s,0n),+0s,2299161j)>