Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.ParseExact returns current date

Tags:

c#

.net

datetime

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 ?

like image 858
user2711965 Avatar asked Dec 11 '22 03:12

user2711965


2 Answers

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

like image 108
Andrey Korneyev Avatar answered Dec 17 '22 07:12

Andrey Korneyev


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.

like image 45
Alexei Levenkov Avatar answered Dec 17 '22 08:12

Alexei Levenkov