Last active
May 28, 2018 19:42
-
-
Save YARG/6ab928f53127e78bcf10 to your computer and use it in GitHub Desktop.
C#/Xamarin iOS - Converts a UTC DateTime to the device local Time Zone as System.DateTime. Also includes functions to convert iOS native date times to System.DateTime and back again.
This file contains 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
/// <summary> | |
/// Converts a UTC datestamp to the local timezone | |
/// </summary> | |
/// <returns>The UTC to local time zone.</returns> | |
/// <param name="dateTimeUtc">Date time UTC.</param> | |
public DateTime ConvertUTCToLocalTimeZone (DateTime dateTimeUtc) | |
{ | |
NSTimeZone sourceTimeZone = new NSTimeZone ("UTC"); | |
NSTimeZone destinationTimeZone = NSTimeZone.LocalTimeZone; | |
NSDate sourceDate = DateTimeToNativeDate (dateTimeUtc); | |
int sourceGMTOffset = sourceTimeZone.SecondsFromGMT (sourceDate); | |
int destinationGMTOffset = destinationTimeZone.SecondsFromGMT (sourceDate); | |
int interval = destinationGMTOffset - sourceGMTOffset; | |
var destinationDate = sourceDate.AddSeconds (interval); | |
var dateTime = NativeDateToDateTime (destinationDate); | |
return dateTime; | |
} | |
/// <summary> | |
/// Converts a System.DateTime to an NSDate | |
/// </summary> | |
/// <returns>The time to native date.</returns> | |
/// <param name="date">Date.</param> | |
public static NSDate DateTimeToNativeDate(DateTime date) | |
{ | |
DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime( | |
new DateTime(2001, 1, 1, 0, 0, 0) ); | |
return NSDate.FromTimeIntervalSinceReferenceDate( | |
(date - reference).TotalSeconds); | |
} | |
/// <summary> | |
/// Converts a NSDate to System.DateTime | |
/// </summary> | |
/// <returns>The date to date time.</returns> | |
/// <param name="date">Date.</param> | |
public static DateTime NativeDateToDateTime(NSDate date) | |
{ | |
DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime( | |
new DateTime(2001, 1, 1, 0, 0, 0) ); | |
return reference.AddSeconds(date.SecondsSinceReferenceDate); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment