Weird… can anyone tell me what’s going wrong here? Is this a bug with strptime?
1.9.3p194 :079 > format = "%m/%-d/%Y %-I:%M:%S %p"
=> "%m/%-d/%Y %-I:%M:%S %p"
1.9.3p194 :080 > now = Time.now.strftime(format)
=> "12/4/2012 1:44:45 PM"
1.9.3p194 :081 > Time.strptime(now, format)
ArgumentError: invalid strptime format - `%m/%-d/%Y %-I:%M:%S %p'
from /Users/fedenusy/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/time.rb:283:in `strptime'
from (irb):81
from /Users/fedenusy/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.9/lib/rails/commands/console.rb:47:in `start'
from /Users/fedenusy/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.9/lib/rails/commands/console.rb:8:in `start'
from /Users/fedenusy/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.9/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
EDIT: to clarify, I’m trying to work with dates in this specific format, eg “12/4/2012 1:44:45 PM”.
The minus (-) flag used to suppress padding in strftime is not supported in strptime.
If you trace the Date#strptime or Time#strptime calls from Rails, you’ll see that you’ll eventually get into the Ruby VM source code for strptime . You’ll see that there is no case in the parser that handles the ‘-‘ character. You can compare this with the implementation of strftime, which does have that case.
So, you can’t use your format string for parsing. You would need to remove the minuses for it to be valid.