I tried the following code:
DateTime dateTime = DateTime.ParseExact("01/02/2013", //string date
"01/02/2013", // string format
CultureInfo.InvariantCulture);
I know the format is incorrect. But why instead of throwing exception it returned the current date dateTime = {24/09/2014 12:00:00 AM}
.
I know the valid format for my date should be MM/dd/yyyy
, But Why it didn't throw an exception. I also tried it with DateTime.TryParseExact
, it returns the current date instead of default(DateTime)
. This actually came up reading this question.
My question is how does this parsing work ?
As per MSDN:
If format defines a date with no time element and the parse operation succeeds, the resulting DateTime value has a time of midnight (00:00:00). If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date of DateTime.Now.Date.
Your format string is the same as value - so parsing goes 'as is' and no exception thrown.
If you will change format string to say, 02/02/2013
- you'll get FormatException
as expected
There is no day/month placeholders in format string. So it literally matches each character (successfully) and returns default (today) values for each component of the date.
Indeed if there is no exact match it will throw error like (notice mismatch between "11/..." and "01/...")
DateTime.ParseExact("11/02/2013",
"01/02/2013", // string format
CultureInfo.InvariantCulture);
Behavior is very similar to some reasonable patterns like "MM/yyyy" - expecting month, than exact match to /
character, than year.
Default values are midnight of current date DateTime.ParseExact:
If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date of DateTime.Now.Date.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With