Last active
August 29, 2015 14:03
-
-
Save teohm/52d4c3e86b94035c0470 to your computer and use it in GitHub Desktop.
Does anyone know why?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, hmm, I tried running 1) and 2) on Ruby 2.1:
-
DateTime.strptime(d.strftime(format), format2)
actually works. -
DateTime.strptime(d.strftime(format), format)
does not work.
Do you get the same results?
@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
I'm not actually sure why do you expect it to work.
Using these 2 different formats, produces different results. When you call
strptime
on them, you need to provide exact format of the string. SoDateTime.strptime(d.strftime(format), format)
will work,DateTime.strptime(d.strftime(format2), format2)
will work, butDateTime.strptime(d.strftime(format), format2)
won't because the result ofstrftime
does not match format ofstrptime
2nd argument.