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
Convert celsius to fahrenheit 1 Celsius is equal to 33.8 Fahrenheit.
Quick Celsius (°C) / Fahrenheit (°F) Conversion:°C.
Celsius to Fahrenheit Conversion FormulaMultiply the °C temperature by 1.8. Add 32 to this number. This is the answer in °F.
Answer: 50° Celsius is equal to 122° Fahrenheit.
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
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