Xamarin 'iOS Foundation NSDate到C# DateTime转换',反之亦然,不考虑夏令时

hjqgdpho  于 2022-12-07  发布在  iOS
关注(0)|答案(3)|浏览(132)

我需要将Cocoa NSDate转换为C# DateTime,反之亦然。
我使用下面的方法来实现这一点:

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);
 }

但事实证明,这种方式并不包括夏令时。
例如,DateTime对象中的时间为DST中的5AM,则返回时间为6AM的NSDate

bz4sfanl

bz4sfanl1#

我很肯定这是一种过时的方法。现在可以将NSDate直接转换为DateTime。

Foundation.NSDate nsDate = // someValue
 DateTime dateTime = (DateTime)nsDate;
wa7juj8i

wa7juj8i2#

基于以下方面的输入:https://forums.xamarin.com/discussion/27184/convert-nsdate-to-datetime
Local TimeDaylight Saving期间会发生变化。因此,始终转换为UTC进行计算,然后根据需要转换为Local time

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);
     }
vcirk6k6

vcirk6k63#

直接转换为NSDate时存在creepy bug
我的解决方案是:

public static NSDate DateTimeToNSDate(this DateTime date)
    {
        var calendar = new NSCalendar(NSCalendarType.Gregorian);
        calendar.TimeZone = NSTimeZone.FromName("UTC");
        var components = new NSDateComponents { Day = date.Day, Month = date.Month, Year = date.Year, Hour = date.Hour,
            Minute = date.Minute, Second = date.Second, Nanosecond = date.Millisecond * 1000000 };
        var result = calendar.DateFromComponents(components);

        return result;
    }

我希望这能帮上忙

相关问题