I am being passed this, 2022-11-01T00:00:00, Date Time as a string. I need to convert it to a DateTime in c# but cannot seem to figure out what exact format the string is in.
I have tried many variations of the following but continue to get String was not recognized as a valid DateTime.
Here is the latest code I have tried:
DateTime test = DateTime.ParseExact(startTime, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
CodePudding user response:
Is there an offset you are trying to account for? I noticed you have a Z at the end of your DateTime format in the latest code you have tried. Removing it in this block of code made it parseable.
string startTime = "2022-11-01T00:00:00";
DateTime test = DateTime.ParseExact(startTime, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
Console.WriteLine(test.ToString()); // 11/1/2022 12:00:00 AM
CodePudding user response:
See https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
string text = "2022-11-01T00:00:00";
if (DateTime.TryParseExact(text, "yyyy-MM-ddTHH:mm:ss", null, System.Globalization.DateTimeStyles.AssumeUniversal, out DateTime dt))
{
Console.WriteLine(dt.ToString("u"));
}
else
{
Console.WriteLine("bad");
}