Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+/- sign in TimeSpan's ParseExact()?

I need to parse a string that specifies the environment's timezone. It looks like +0100 or -0530, specifying the offset from the UTC time zone.

In these strings, the plus/minus sign is always there. I want to parse this with the TimeSpan.ParseExact() method, and I'm quite sure that there is a way. The Parse() method knows how to deal with a minus sign, but the ParseExact() method's documentation does not mention anything about signs whatsoever.

So far, the format I'm using is hhmm, but this will need to be prefixed by something that deals with the +/- sign. Can anyone please point me in the right direction?

like image 327
Lee White Avatar asked Jan 07 '23 09:01

Lee White


2 Answers

You could check if it starts with -, then apply the appropriate format string:

string[] timespans = { "-0530", "+0100" };
foreach (string timespan in timespans)
{
    bool isNegative = timespan.StartsWith("-");
    string format = isNegative ? "\\-hhmm" : "\\+hhmm";
    TimeSpanStyles tss = isNegative ? TimeSpanStyles.AssumeNegative : TimeSpanStyles.None;
    TimeSpan ts;
    if (TimeSpan.TryParseExact(timespan, format, null, tss, out ts))
    {
        Console.WriteLine("{0} successfully parsed to: {1}", timespan, ts);
    }
    else
    {
        Console.WriteLine("Could not be parsed: {0}", timespan);
    }
}

Note that i use TimeSpanStyles.AssumeNegative in TryParseExact, otherwise the timespans would be always positive even if they are prepended with a minus.

like image 96
Tim Schmelter Avatar answered Jan 09 '23 21:01

Tim Schmelter


This should work for timezone offsets:

var dt = DateTime.ParseExact("14-oct-2015 08:22:00 +01:00","dd-MMM-yy HH:mm:ss zzz", culture);

But this only works for DateTime, not TimeSpan, as timezone information is not supported in TimeSpan strings.

like image 34
Sk93 Avatar answered Jan 09 '23 21:01

Sk93