Alex Strizhak
Alex Strizhak

Reputation: 990

Bug in `Date#strtime`? It parses days which more than 30/31 in a month, confusing them with the years

Why the string of date with specific format is successfully parsed by strptime method with an explicit different format?

need to explicitly accepted format date for API

$ ruby -v
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-linux]
$ irb
irb(main):001:0> require 'date'
=> true
irb(main):002:0> Date.strptime('01-01-1970', '%Y-%m-%d')
=> #<Date: 0001-01-19 ((1721442j,0s,0n),+0s,2299161j)>
irb(main):003:0> Date.strptime('01-01-1970', '%Y-%m-%d').to_s
=> "0001-01-19"
irb(main):004:0> Date.strptime('01-01-1970', '%Y-%m-%d').year
=> 1
irb(main):005:0> Date.strptime('01-01-1970', '%Y-%m-%d').day
=> 19

Expect: test passed

it 'raises an exception when wrong format' do
 expect { Date.strptime('01-01-1970', '%Y-%m-%d') }.to raise_exception(ArgumentError, 'invalid format')
end

Actual: expected ArgumentError with "invalid format" but nothing was raised

Upvotes: 0

Views: 72

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230561

You have two hidden questions, I think.

Why is 01 a valid match for %Y (which means "year including century")

Because why assume 4 digit years? Otherwise you wouldn't be able to specify 3-digit years (for example, year 882 was when Kiev became capital of Rus). Or maybe in this case you did mean year 1. Ruby has no idea.

Why is 1970 a match for %d?

Because that's how strptime(3) works (which it's supposed to be compatible with). Once format descriptor %d ("day, 1-31") is satisfied with 19, the string stops being processed.

The return value of the function is a pointer to the first character not processed in this function call. In case the input string contains more characters than required by the format string the return value points right after the last consumed input character.

Upvotes: 7

Related Questions