Skip to content

Instantly share code, notes, and snippets.

@teohm
Last active August 29, 2015 14:03
Show Gist options
  • Save teohm/52d4c3e86b94035c0470 to your computer and use it in GitHub Desktop.
Save teohm/52d4c3e86b94035c0470 to your computer and use it in GitHub Desktop.
Does anyone know why?
require 'date'
# 1) this doesn't work, why?
format = "%-m/%-d/%Y %-l:%M:%S %p"
d = DateTime.new(2014,6,5,1,5,9)
d == DateTime.strptime(d.strftime(format), format) # raised ArgumentError: invalid date
# 2) this works, why?
format = "%-m/%-d/%Y %-l:%M:%S %p"
format2 = "%m/%d/%Y %l:%M:%S %p"
d = DateTime.new(2014,6,5,1,5,9)
d == DateTime.strptime(d.strftime(format), format2)
@arnvald
Copy link

arnvald commented Jun 26, 2014

I'm not actually sure why do you expect it to work.

irb(main):058:0> DateTime.new(2014,6,5,1,5,9).strftime("%-m/%-d/%Y %-l:%M:%S %p")
=> "6/5/2014 1:05:09 AM"
irb(main):059:0> DateTime.new(2014,6,5,1,5,9).strftime("%m/%d/%Y %l:%M:%S %p")
=> "06/05/2014  1:05:09 AM"

Using these 2 different formats, produces different results. When you call strptime on them, you need to provide exact format of the string. So DateTime.strptime(d.strftime(format), format) will work, DateTime.strptime(d.strftime(format2), format2) will work, but DateTime.strptime(d.strftime(format), format2) won't because the result of strftime does not match format of strptime 2nd argument.

@teohm
Copy link
Author

teohm commented Jun 26, 2014

@arnvald, hmm, I tried running 1) and 2) on Ruby 2.1:

  1. DateTime.strptime(d.strftime(format), format2) actually works.

  2. DateTime.strptime(d.strftime(format), format) does not work.

Do you get the same results?

@teohm
Copy link
Author

teohm commented Jun 26, 2014

@arnvald, I found this:
https://www.ruby-forum.com/topic/4416958

http://www.ruby-doc.org/stdlib-2.1.2/libdoc/date/rdoc/DateTime.html#method-c-strptime
"strptime does not support specification of flags and width unlike strftime."

(:mindblown:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment