Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin 'iOS Foundation NSDate to C# DateTime conversion' and vice versa not accounting for DayLight saving

I need to convert Cocoa NSDate to C# DateTime and vice versa.

I am using the following method to achieve this:

 public static DateTime NSDateToDateTime (Foundation.NSDate date)
 {
    DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime (
        new DateTime (2001, 1, 1, 0, 0, 0));
   return reference.AddSeconds (date.SecondsSinceReferenceDate);
 }

 public static Foundation.NSDate DateTimeToNSDate (DateTime date)
 {
    DateTime reference = TimeZone.CurrentTimeZone.ToLocalTime (
        new DateTime (2001, 1, 1, 0, 0, 0));
    return Foundation.NSDate.FromTimeIntervalSinceReferenceDate (
        (date - reference).TotalSeconds);
 }

But it turns out, this way it is not accounting for Daylight Saving.

Eg. DateTime object in which the time was 5AM in DST returns NSDate with time 6AM.

like image 537
7vikram7 Avatar asked Apr 18 '17 10:04

7vikram7


2 Answers

I'm pretty sure this is an outdated approach. You can cast a NSDate directly to a DateTime now.

 Foundation.NSDate nsDate = // someValue
 DateTime dateTime = (DateTime)nsDate;
like image 174
Chris Koiak Avatar answered Nov 07 '22 14:11

Chris Koiak


Based on inputs from: https://forums.xamarin.com/discussion/27184/convert-nsdate-to-datetime


Local Time changes during Daylight Saving. Hence, always convert to UTC to do the calculations, then convert to Local time if needed.

     public static DateTime NSDateToDateTime (Foundation.NSDate date)
     {
        DateTime reference = new DateTime(2001, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var utcDateTime = reference.AddSeconds(date.SecondsSinceReferenceDate);
        return utcDateTime.ToLocalTime();
     }

     public static Foundation.NSDate DateTimeToNSDate (DateTime date)
     {
        DateTime reference = new DateTime(2001, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
        var utcDateTime = date.ToUniversalTime();
        return Foundation.NSDate.FromTimeIntervalSinceReferenceDate((utcDateTime - reference).TotalSeconds);
     }
like image 43
7vikram7 Avatar answered Nov 07 '22 15:11

7vikram7