user3458219
user3458219

Reputation: 151

DateTime.ParseExact doesn't work for "yyyy-MM-dd HH:mm:ss"

I have System.DateTime.Now stored in a variable called StartDate (variable is of type DateTime?).

I am converting it to string as below:

string temp = StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss")

Now the temp has value in "yyyy-MM-dd HH:mm:ss".

Now I want to again convert string temp to DateTime so, I am doing as below:

DateTime.ParseExact(temp,"yyyy-MM-dd HH:mm:ss",null)

but this doesn't work.

It always returns date in a same format as System.DatTime.Now. It should return value in "yyyy-MM-dd HH:mm:ss" format.

Upvotes: 3

Views: 5615

Answers (1)

Hans Kesting
Hans Kesting

Reputation: 39329

A value of type DateTime doesn't have a particular format. That date-and-time is stored as a couple of integer values (not one for each component, but much more compact).

When you parse a string, that date represented in that string is stored as those integers.

Only when you do a .ToString() (possibly with some format) you get a string representation of that date in a particular format.

When you hover over the DateTime value in the debugger, you see the result of a plain .ToString(), using some specific current culture.

The difference between Parse and ParseExact is that Parse tries several formats (and may fail on a string like "2/3/2017" - FEB 3rd or 2nd MAR?) while with ParseExact you supply one or more formats yourself. In both cases you end up with a value of the same DateTime type.

Upvotes: 3

Related Questions