Convert time in UIDatePicker to local

By July 24, 2012Blog

When working with UIDatePicker time mode, it is typical that the time is picked in UTC and it needs to be converted to the local time and DateTime representation for purposes of showing it, setting up an alarm and such.

 

NSDate sourceDate = picker.Date;
 
NSTimeZone sourceTimeZone = new NSTimeZone ("UTC");
NSTimeZone destinationTimeZone = NSTimeZone.LocalTimeZone;
 
int sourceGMTOffset = sourceTimeZone.SecondsFromGMT (sourceDate);
int destinationGMTOffset = destinationTimeZone.SecondsFromGMT (sourceDate);
int interval = destinationGMTOffset - sourceGMTOffset;
 
var destinationDate = sourceDate.AddSeconds (interval);
 
var dateTime = new DateTime(2001, 1, 1, 0, 0, 0).AddSeconds(destinationDate.SecondsSinceReferenceDate);

 

Happy coding!