Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse Timezone Offset string?

I retrieve a value from my database of a timeZone offset. The value that I get is in time.

For example, it could be "-5:00", "+7:30", "+3:00", etc.

How do I convert that to a double so I can do an AddHours() call on a DateTime object?

like image 230
rmh Avatar asked Feb 12 '23 10:02

rmh


2 Answers

John Koerner answer have a few cons;

  • Based on + or -, additional string operations might be needed. It can handle - or no sign, but it can't handle + character itself.
  • Since his used TimeSpan.Parse(string) overload, if CurrentCulture's TimeSeparator is not : (I know it's rare) this method throws FormatException.

Besides on these, I think TimeSpan.Parse is not the best way to parse an UTC Offset. Indeed an Offset is also a time interval, but this value might not be always parsed successfully.

I think the best option is DateTimeOffset.TryParseExact method with zzz format specifier. Since DateTimeOffset.Offset property returns it's value as TimeSpan, it is perfectly can be use with DateTime.

For example;

var s = "+05:30";
DateTimeOffset dto;
var dtop = DateTimeOffset.TryParseExact(s, "zzz",
                 CultureInfo.InvariantCulture,
                 DateTimeStyles.None, out dto);
var today = DateTime.Today;
today = today.AddHours(dto.Offset.TotalHours);

This works for all possibile UTC Offset formats (±[hh]:[mm], ±[hh][mm], or ±[hh]).

like image 153
Soner Gönül Avatar answered Feb 23 '23 07:02

Soner Gönül


Use the TimeSpan.Parse method:

var time = "+7:30";
time = time.Replace("+", "");  // Remove the + if it is there.

var hours = TimeSpan.Parse(time).TotalHours;
like image 30
John Koerner Avatar answered Feb 23 '23 07:02

John Koerner