I am new to both .NET and stackoverflow, so I might be wrong, but here goes:
Using TimeZoneInfo.ConvertTimeFromUtc will allow you to use daylight saving time and convert to the correct time according to the time zone + possible DST offset. However, the offset itself in the resulting object will display the offset for standard time and not include daylight saving. Therefore, if you want to make ToString on the object, you will get the correct time (in hours and minutes), but the wrong offset during daylight saving time, which can lead to the wrong time later in the code.
If you use GetUtcOffset to get the offset within a certain time, and then execute ToOffset on the DateTimeOffset, then both the hours / minutes and the offset itself will be correctly converted, and you can safely execute ToString.
string ExpectedDateTimePattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss''zzz"; string timeZoneId = "FLE Standard Time"; string dateTimestr = "2017-10-09T09:00:00+02:00"; DateTimeOffset dto = DateTimeOffset.Parse(dateTimeStr); TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); TimeSpan offset = zone.GetUtcOffset(dto); dto = dto.ToOffset(offset); string localTime = dto.ToString(ExpectedDateTimePattern);
localTime will return "2017-10-09T10: 00: 00 + 03: 00".
datetimeoffset timezoneinfo getutcoffset
Niels Pein Nov 07 '17 at 12:03 2017-11-07 12:03
source share