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?
John Koerner answer have a few cons;
+
or -
, additional string operations might be needed. It can handle -
or no sign, but it can't handle +
character itself.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]
).
Use the TimeSpan.Parse method:
var time = "+7:30";
time = time.Replace("+", ""); // Remove the + if it is there.
var hours = TimeSpan.Parse(time).TotalHours;
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