Joerg
Joerg

Reputation: 3823

DateTime.strptime can't parse date string

I don't understand why the following Ruby 2.4 code fails:

irb(main):006:0> require 'date'
=> false
irb(main):007:0> fmt = "%-m/%-d/%Y %-l:%M:%S %p"
=> "%-m/%-d/%Y %-l:%M:%S %p"
irb(main):008:0> DateTime.now.strftime(fmt)
=> "1/30/2018 7:42:44 AM"
irb(main):009:0> DateTime.strptime("1/30/2018 7:42:44 AM", fmt)
ArgumentError: invalid date
  from (irb):9:in `strptime'
  from (irb):9
  from /usr/local/bin/irb:11:in `<main>'
irb(main):010:0>

The datetime format works when I format a date, but the same format string fails when I try to parse a date string in that format.

Upvotes: 2

Views: 675

Answers (2)

Nabin Paudyal
Nabin Paudyal

Reputation: 1639

The error is because the format fmt you have provided doesn't match the DateTime string you have provided.

Change your format from

fmt = "%-m/%-d/%Y %-l:%M:%S %p"

into

fmt = "%m/%d/%Y %l:%M:%S %p"

Hope this helps.

Upvotes: 2

moritz
moritz

Reputation: 25767

Its because strptime doesn't support the flags in the format you are using, have a look at http://ruby-doc.org/stdlib-2.4.2/libdoc/date/rdoc/DateTime.html#method-c-strptime

Upvotes: 4

Related Questions