diff --git a/spec/std/time/format_spec.cr b/spec/std/time/format_spec.cr index 3a95d50d0eea..08baa2e910fd 100644 --- a/spec/std/time/format_spec.cr +++ b/spec/std/time/format_spec.cr @@ -204,6 +204,12 @@ describe Time::Format do Time.parse!("2017-12-01 20:15:13 +01:00", "%F %T %:z").to_s("%F %T %:z").should eq "2017-12-01 20:15:13 +01:00" end + it "gives nice error message when end of input is reached (#12047)" do + expect_raises(Time::Format::Error, "Expected '-' but the end of the input was reached") do + Time.parse!("2021-01", "%F") + end + end + it "parses" do parse_time("2014", "%Y").year.should eq(2014) parse_time("19", "%C").year.should eq(1900) diff --git a/src/time/format/parser.cr b/src/time/format/parser.cr index e5587d55e753..95bac1a5799d 100644 --- a/src/time/format/parser.cr +++ b/src/time/format/parser.cr @@ -502,6 +502,14 @@ struct Time::Format end def char(char, *alternatives) + unless @reader.has_next? + if alternatives.empty? + raise "Expected #{char.inspect} but the end of the input was reached" + else + raise "Expected one of #{char.inspect}, #{alternatives.join(", ", &.inspect)} but reached the input end" + end + end + unless char?(char, *alternatives) raise "Unexpected char: #{current_char.inspect}" end