How to convert timezone offset text "+01:00" to timespan
Asked Answered
J

2

6

I have an API which will accept timezone offset as string. I need to convert the timezone to TimeSpan and add the timespan with the data i have which is in UTC. Here is what i'm trying.

private bool TryGetHrAndMinFromTimeZone(string timeZone, out TimeSpan result)
    {
        try
        {
            var isPositive = !timeZone.StartsWith("-");
            var hrAndMin = string.Concat(timeZone.Where(x => x != '-' && x != '+')).Split(':');
            var hr = int.Parse(hrAndMin[0]);
            var min = int.Parse(hrAndMin[1]);
            result = isPositive ? new TimeSpan(hr, min, 0) : new TimeSpan(-hr, -min, 0);
            return true;
        }
        catch (Exception)
        {
            throw new Exception(string.Format("Provided TimeZone '{0}' is Invalid ", timeZone));
        }
    }

Is there any better option to do it?

Judicial answered 23/12, 2019 at 5:22 Comment(1)
Hey, try this --> TimeSpan.TryParse("-07:00", out TimeSpan ts)Corroborate
C
4

you can try

TimeSpan.TryParse("-07:00", out TimeSpan ts) //for -07:00
TimeSpan.TryParse("07:00", out TimeSpan ts) //for +07:00

for more information https://learn.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones#converting-datetimeoffset-values

Corroborate answered 23/12, 2019 at 5:37 Comment(2)
Thanks for the input. It works nicely with -ve timezone offsets. But not with +ve timezone offsets. can you provide an input on that?Judicial
@AkbarBadhusha remove plus(+) sign from the string.Corroborate
S
3

The DateTimeOffset type can parse offsets of this format using the zzz specifier. Thus you can write a function such as the following:

static TimeSpan ParseOffset(string s)
{
    return DateTimeOffset.ParseExact(s, "zzz", CultureInfo.InvariantCulture).Offset;
}

Another approach, you can parse with TimeSpan.ParseExact if you strip off the sign first and handle it yourself:

static TimeSpan ParseOffset(string s)
{
    var ts = TimeSpan.ParseExact(s.Substring(1), @"hh\:mm", CultureInfo.InvariantCulture);
    return s[0] == '-' ? ts.Negate() : ts;
}

Or, as Manish showed in his answer, you can let TimeSpan.Parse attempt to figure out the string. It works if you remove the + sign first.

static TimeSpan ParseOffset(string s)
{
    return TimeSpan.Parse(s.Replace("+", ""), CultureInfo.InvariantCulture);
}
Schofield answered 23/12, 2019 at 18:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.