so I have this string "2022-12-20T23:59:59.000Z" and I need to convert it to date time to be able to make a date comparison.
I used DateTime.Parse("2022-12-20T23:59:59.000Z") and returned 30/11/2022 21:00:00 (I’m using the date format dd/MM/yyyy) what’s wrong? the correct value should be 20-12-2022 23:59:59
The issue is that the DateTime.Parse() method is interpreting the input string as a local time, rather than as a UTC time. The input string "2022-12-20T23:59:59.000Z" includes the "Z" at the end, which is a standard notation for indicating that the time is in UTC.
You can use the DateTime.ParseExact() method with a "yyyy-MM-ddTHH:mm:ss.fffZ" format string to correctly parse the input string as a UTC time. Then you can use .ToLocalTime() method to convert it to local time.
string input = "2022-12-20T23:59:59.000Z"; DateTime dateTime = DateTime.ParseExact(input, "yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal); Console.WriteLine(dateTime.ToLocalTime().ToString("dd/MM/yyyy HH:mm:ss"));
This will correctly parse the input string and convert it to local time, resulting in the output "20/12/2022 23:59:59".
It’s important to note that when working with date and time, it’s best practice to always store and manipulate them in UTC and convert them to local time just for display purposes.