2

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.

Joerg
  • 3,553
  • 4
  • 32
  • 41

2 Answers2

4

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

moritz
  • 25,477
  • 3
  • 41
  • 36
  • So the specified flag "-" for example (or any flags) does not work with `strptime`. I need to omit them from the format string. Thanks for that! Missed that little bit in the documentation. – Joerg Jan 30 '18 at 08:06
2

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.

Nabin Paudyal
  • 1,591
  • 8
  • 14
  • That's it - thank you! I accepted the other answer as it explained that strptime doesn't support flags - the reason why the `fmt` doesn't "match" the datetime string. – Joerg Jan 30 '18 at 08:18