convert C# date time to string and back

axe picture axe · May 29, 2012 · Viewed 37.1k times · Source

I'm converting C# date time to string. Later when I convert it back to DateTime object it appears that they are not equal.

const string FMT = "yyyy-MM-dd HH:mm:ss.fff";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());

Here is the example. Looks like everything is included in string format, when I print date both displays the same, but when I compare objects or print date in binary format I see the difference. It looks strange to me, could you please explain what is going on here?

Here is the output for the code above.

-8588633131198276118
634739049656490000

Answer

Oded picture Oded · May 29, 2012

You should use the roundtrip format specifier "O" or "o" if you want to preserve the value of the DateTime.

The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.

Using your code (apart from changing the format string):

const string FMT = "O";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());

I get:

-8588633127598789320
-8588633127598789320