Neerav Dodhia
Neerav Dodhia

Reputation: 178

DateTime.TryParseExact returns true if date string matches format string

Ran into an issue when running a unit test to ensure the correct response from an api when an invalid datetime format sting is passed in. When passing in a date string as "0711" and format "0711", the api was not returning an error and instead set this date to today.

With eg the examples below - DateTime.TryParseExact() returns true setting the date to today.

DateTime.TryParseExact("1019", "1019", null, System.Globalization.DateTimeStyles.AssumeLocal, out result)

DateTime.TryParseExact("1a111", "1a111", null, System.Globalization.DateTimeStyles.AssumeLocal, out result)

If the strings do not match eg

DateTime.TryParseExact("1019", "1018", null, System.Globalization.DateTimeStyles.AssumeLocal, out result)

this correctly returns false.

Is this expected behaviour? If so can canyone explain the internal workings? What is a reliable way of mitigating this other than just checking to see if the strings match eachother?

Upvotes: 2

Views: 307

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156938

Is this expected behavior?

Yes.

If so can anyone explain the internal workings?

The numbers you put in are just read as literals, and they do match. There is no HH, mm or similar identifiers in your parse string, so there is no actual date to parse. It defaults to DateTime.Now.

What is a reliable way of mitigating this other than just checking to see if the strings match each other?

Use an actual date time format string, like HHmm.

Upvotes: 1

Related Questions