Home > other >  C# convert string with time zone to datetime HH:mm (UTC)
C# convert string with time zone to datetime HH:mm (UTC)

Time:09-19

I'm trying to convert a string to DateTime. The string includes the Time zone.

here is how it looks like

HH:mm (time zone)

04:47 (CEST).

The timezone isn't always the same. I have tried using an array of formats, but is there any better way to convert that? I also readed the microsoft doc but couldn't find any way to convert this one

Tryed

string[] formats = new[] { "HH:mm (CEST)", "HH:mm (CET)" };
var processedData = DateTime.ParseExact(
    "04:47 (CEST)",
    formats,
    CultureInfo.InvariantCulture,
    DateTimeStyles.None);

Console.WriteLine(processedData);

CodePudding user response:

You can replace them with the timezone offset and then use the right ParseExact-format and DateTimeStyles.AdjustToUniversal to get the universal time(UTC):

public static void Main(string[] args)
{
    string[] inputs = { "04:47(CEST)", "14:47(CET)" };
    DateTime?[] utcTimes = Array.ConvertAll(inputs, TryParseUtcTime);
}

private static DateTime? TryParseUtcTime(string input)
{
    input = input.Replace("(CEST)", "  2").Replace("(CET)", "  1");
    if(DateTime.TryParseExact(input, "HH:mm z", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out DateTime dt))
    {
        return dt;
    }

    return null;
}

Demo: https://dotnetfiddle.net/qKgvI1

  • Related