Created
April 4, 2018 16:02
-
-
Save alexsandro-xpt/b99532eeff31f126ba5acdb4fdbf8d9c to your computer and use it in GitHub Desktop.
TimeZone Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Tz | |
| { | |
| /// <summary> | |
| /// Maintain date time values from UTC DateTime but change her offset for espefict time zone. | |
| /// </summary> | |
| /// <param name="localDate">DateTime in UTC</param> | |
| /// <param name="timeZoneId">IANA time zone format</param> | |
| /// <returns></returns> | |
| public static DateTime ShiftUtcDateTimeToTimeZoneOffSet(DateTime localDate, string timeZoneId) | |
| { | |
| if (localDate.Kind != DateTimeKind.Utc) throw new Exception($"Can not convert to {timeZoneId} because {localDate} is not set as UTC kind."); | |
| if (string.IsNullOrWhiteSpace(timeZoneId)) | |
| { | |
| return localDate; | |
| } | |
| localDate = DateTime.SpecifyKind(localDate, DateTimeKind.Unspecified); | |
| TimeZoneInfo tz; | |
| if (System.Environment.OSVersion.Platform == PlatformID.Win32NT) | |
| { | |
| tz = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timeZoneId)); | |
| } | |
| else | |
| { | |
| tz = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); | |
| } | |
| var destinationTimeZone = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows("UTC")); | |
| if (tz.IsInvalidTime(localDate)) | |
| { | |
| if (!tz.IsInvalidTime(localDate.AddHours(1))) | |
| { | |
| localDate = localDate.AddHours(1); | |
| } | |
| else if (!tz.IsInvalidTime(localDate.AddHours(-1))) | |
| { | |
| localDate = localDate.AddHours(-1); | |
| } | |
| } | |
| return TimeZoneInfo.ConvertTime(localDate, tz, destinationTimeZone).ToUniversalTime(); | |
| } | |
| public static DateTime FromLocal(DateTime localDate, string timeZoneId) | |
| { | |
| if (localDate.Kind == DateTimeKind.Local) | |
| { | |
| return localDate.ToUniversalTime(); | |
| } | |
| TimeZoneInfo tz; | |
| if (System.Environment.OSVersion.Platform == PlatformID.Win32NT) | |
| { | |
| tz = TimeZoneInfo.FindSystemTimeZoneById(TZConvert.IanaToWindows(timeZoneId)); | |
| } | |
| else | |
| { | |
| tz = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId); | |
| } | |
| return TimeZoneInfo.ConvertTimeToUtc(localDate, tz); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment