Как разобрать строку смещение часового пояса?

Обновить

April 2019

Просмотры

718 раз

1

Я извлечь значение из моей базы данных на смещение часового пояса. Значение, которое я получаю во время.

Например, это может быть "-5:00", "+7:30", "+3:00"и т.д.

Как преобразовать , что двойной , так что я могу сделать AddHours()вызов на DateTimeобъект?

rmh

2 ответы

2

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]).

2

Use the TimeSpan.Parse method:

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

var hours = TimeSpan.Parse(time).TotalHours;