Reputation: 238667
I am using Ruby 2.1 in a Rails 4.0.2 application. I need to convert a string into a valid Date object, but everything I try says it's an invalid date:
# in irb
date = 'Feb 9'
Date.strptime(date, '%m %-d')
# NoMethodError: undefined method `strptime' for Date:Class
# in Rails console
date = 'Feb 9'
Date.strptime(date, '%m %-d')
# ArgumentError: invalid date
# from (irb):2:in `strptime'
date += ' ' + Time.now.year.to_s
Date.strptime(date, '%m %-d %Y')
# ArgumentError: invalid date
How can I parse a date in this abbreviated format?
Upvotes: 1
Views: 1006
Reputation: 19228
The format string is wrong, it should be:
require 'date'
date = 'Feb 9'
Date.strptime(date, '%b %d').to_s
# => "2014-02-09"
%m
would match a month number (1-12) while %b
matches the abbreviated month name according to current locale. As the Ruby documentation says, available formats are documented in strptime(3) manual page.
Or use the Date.parse
method:
Date.parse(date).to_s
# => "2014-02-09"
Update: I didn't notice it before, the -
modifier to match the unpadded day number breaks strptime
:
Date.strptime('9', '%-d').to_s
# ArgumentError: invalid date
Date.strptime('9', '%d').to_s
# => "2014-02-09"
Upvotes: 2
Reputation: 160181
"Feb" is not a valid month number.
[1] pry(main)> date = 'Feb 9'
"Feb 9"
[2] pry(main)> Date.strptime(date, "%b %d")
Sun, 09 Feb 2014
E.g.,
%m - Month of the year, zero-padded (01..12) %_m blank-padded ( 1..12) %-m no-padded (1..12) %B - The full month name (``January'') %^B uppercased (``JANUARY'') %b - The abbreviated month name (``Jan'') %^b uppercased (``JAN'') %h - Equivalent to %b
Upvotes: 4