0

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;
}
Peter Morris
  • 20,174
  • 9
  • 81
  • 146
  • 2
    Just a minor note.. +5 isn't a timezone, it's an offset. There are many more timezones than there are offsets, and each timezone has particular rules about how it uses offsets.. – Caius Jard Jun 01 '21 at 16:34
  • Also, https://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in-c-sharp might be of assistance – Caius Jard Jun 01 '21 at 17:06

0 Answers0