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.
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;
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With