Reputation: 2627
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?
Upvotes: 6
Views: 2260
Reputation: 241808
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);
}
Upvotes: 3
Reputation: 1197
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
Upvotes: 4