I have a requirement to parse dates in ISO format and convert them to UTC DateTime values.
When the input string ends with a Z (for Zulu time) or an explicit timezone (e.g. +05:00
) then DateTime.Parse will parse the date/time correctly because it is explicit.
However, when the input does not end with either (e.g. 2021-06-01T12:34:56.789
) then I need to convert it as UK time, regardless of the TimeZone the server is running within.
I wrote the following method which does the trick, but I am not massively confident in the approach even though it seems to work. Is there a better way?
public static bool TryParseIsoUKDateTime(string value, out DateTime result)
{
if (!DateTimeOffset.TryParse(value, out DateTimeOffset dateTimeOffset))
{
result = DateTime.MinValue;
return false;
}
result = new DateTime(dateTimeOffset.DateTime.Ticks, DateTimeKind.Utc);
if (DateString.IndexOf("+") > -1)
{
result -= dateTimeOffset.Offset;
return true;
}
if (!value.EndsWith("Z",StringComparison.OrdinalIgnoreCase))
{
result -= UKTimeZone.GetUtcOffset(result);
return true;
}
return true;
}