I recently changed my website hosting provider and the new server's time zone is set to UTC.
I have written the following code but it doesn't work as expected. Am I doing something wrong?
When I call DateTime.Now the time returned is indeed UTC time, but to my understanding DateTime.Now (passed to the method) should be of 'Kind' Utc. But the method is returning the same UTC time, as opposed to converting to local time (desired result).
DEFAULT_TIMEZONE is string constant: AUS Eastern Standard Time
public static DateTime UTCToLocalTime(DateTime dt, string destinationTimeZone) { DateTime dt_local = dt; try { if (dt.Kind == DateTimeKind.Local) return dt_local; if (string.IsNullOrEmpty(destinationTimeZone)) destinationTimeZone = DEFAULT_TIMEZONE; TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZone); dt_local = TimeZoneInfo.ConvertTimeFromUtc(dt, tzi); if (tzi.IsDaylightSavingTime(dt_local)) dt_local = dt_local.AddHours(-1); } catch (TimeZoneNotFoundException) { AddLogEntry("Registry does not define time zone: '" + destinationTimeZone + "'."); } catch (InvalidTimeZoneException) { AddLogEntry("Registry data for time zone: '" + destinationTimeZone + "' is not valid."); } catch (Exception ex) { ProcessError(ex); } return dt_local; } Calling the method:
DateTime dt = gFunc.UTCToLocalTime(DateTime.Now, string.Empty); UPDATE: CODE CHANGES
I misunderstood how 'Kind' works. I thought if the OS timezone was set to UTC then a call to DateTime.Now would be of 'Kind' Utc. The following code now works for me as expected.
public static DateTime UTCNowToLocal(string destinationTimeZone) { DateTime dt_now = DateTime.UtcNow; try { if (string.IsNullOrEmpty(destinationTimeZone)) destinationTimeZone = DEFAULT_TIMEZONE; TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(destinationTimeZone); dt_now = TimeZoneInfo.ConvertTimeFromUtc(dt_now, tzi); if (tzi.IsDaylightSavingTime(dt_now)) dt_now = dt_now.AddHours(-1); } catch (TimeZoneNotFoundException) { AddLogEntry("Registry does not define time zone: '" + destinationTimeZone + "'."); } catch (InvalidTimeZoneException) { AddLogEntry("Registry data for time zone: '" + destinationTimeZone + "' is not valid."); } catch (Exception ex) { ProcessError(ex); } return dt_now; }
DateTime.UtcNow?DateTime.Nowis going to be in UTC, and theKindset toLocal(sinceDateTime.Nowalways sets theKindtoLocal). That your hosting provider decided the local time zone is UTC is irrelevant toKind; its value is determined by where the value is pulled from, not by the value.DateTime.UtcNow(perhapsvar diff = DateTime.UtcNow.Subtract(dt);) and decide the minimum difference allowable.DateTimeOffsetgenerally provides better time zone handling thanDateTime, so you may prefer to use that type instead.