Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert C# date time to string and back

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 
like image 764
axe Avatar asked May 29 '12 12:05

axe


People also ask

What is C equal to in Fahrenheit?

Convert celsius to fahrenheit 1 Celsius is equal to 33.8 Fahrenheit.

What does C mean in conversion?

Quick Celsius (°C) / Fahrenheit (°F) Conversion:°C.

How do you convert Celsius to normal values?

Celsius to Fahrenheit Conversion FormulaMultiply the °C temperature by 1.8. Add 32 to this number. This is the answer in °F.

What temperature in Fahrenheit is 50 C?

Answer: 50° Celsius is equal to 122° Fahrenheit.


1 Answers

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 
like image 53
Oded Avatar answered Oct 17 '22 14:10

Oded