5

I would expect this code to give me an ArgumentError: invalid date error. In Ruby 2.0.0 irb:

irb(main):003:0> Date.strptime('05-10-2014', '%Y-%m-%d')
=> #<Date: 0005-10-20 ((1723177j,0s,0n),+0s,2299161j)>

Am I doing something wrong or will Ruby accept a 2-digit year even when I specify %Y?

I am looking at testing user input. In this case my program is expecting it in the %Y-%m-%d and the input date was "entered" in the wrong format, but strptime says it's ok.

J Graham
  • 181
  • 1
  • 7
  • The [document](http://ruby-doc.org/stdlib-2.1.1/libdoc/date/rdoc/Date.html#method-i-strftime) says four digits at least. What you report goes against it. – sawa Jul 16 '14 at 19:47
  • It is misleading to use a string like `'05-10-2014'`. Use `'05-10-20'`. – sawa Jul 16 '14 at 19:55
  • How is it misleading to use a 4-digit year? – J Graham Jul 16 '14 at 20:00
  • 3
    I think the OP is asking why strptime is accepting '05-10-2014' as a valid format when a format of '%Y-%m-%d' is required. It should be raising an error that the data given does not match the format. – infused Jul 16 '14 at 20:01
  • @JGraham No, you are not using a 4-digit year. You are using a 2-digit day of month `20` followed by a sequence `14` that does not contribute to parsing. Why is it not misleading to leave a dummy `14`? What is the purpose of leaving it? – sawa Jul 16 '14 at 20:02
  • 2
    @infused has it correct. The date string I'm passing in is incorrect on purpose, yet strptime says it's valid. – J Graham Jul 16 '14 at 20:05
  • You just try `-d` and `-m`.. This is more **stricter** than `m` and `d`. – Arup Rakshit Jul 16 '14 at 20:08
  • @sawa yes the string is incorrect. But why does strptime say it's valid? And please - there's no need to insult my "comprehension skill" here. – J Graham Jul 16 '14 at 20:09
  • @ArupRakshit I tried the `-d` and `-m` and it always gave me `invalid date` even when I entered a correct one. Are those just for use with `strftime`? – J Graham Jul 16 '14 at 20:16

1 Answers1

7

There was a Ruby bug opened for this issue last year, but it was rejected. I guess the Ruby team feels that this is valid behavior.

https://bugs.ruby-lang.org/issues/8941

infused
  • 24,000
  • 13
  • 68
  • 78