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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With