iOS + DayLight节省了时间

时间:2016-03-18 12:21:24

标签: ios objective-c nsdate nsdateformatter nstimezone

我将UTC时间转换为本地TimeZone(在我的情况下为DTS)后面临一个问题,错过了一小时。

UTC时间转换为当地时间的功能:

+ (NSString *) convertUTCTimeToLocalTime:(NSString *)dateString {
    @try {

        //Log: dateString - 2016-03-08 06:00:00 // Time in UTC
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

        NSTimeZone *gmtTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
        //Log: gmtTimeZone - GMT (GMT) offset 0

        [dateFormatter setTimeZone:gmtTimeZone];
        NSDate *dateFromString = [dateFormatter dateFromString:dateString];
        //Log: dateFromString - 2016-03-08 06:00:00 +0000

        [NSTimeZone setDefaultTimeZone:[NSTimeZone systemTimeZone]];
        NSTimeZone * sourceTimeZone = [NSTimeZone defaultTimeZone];
        //Log: sourceTimeZone - America/New_York (EDT) offset -14400 (Daylight)

        // Add daylight time
        BOOL isDayLightSavingTime = [sourceTimeZone isDaylightSavingTimeForDate:dateFromString];
        if (isDayLightSavingTime) {
            NSTimeInterval timeInterval = [sourceTimeZone  daylightSavingTimeOffsetForDate:dateFromString];
            dateFromString = [dateFromString dateByAddingTimeInterval:timeInterval];
        }

        [dateFormatter setLocale:[NSLocale currentLocale]];
        [dateFormatter setTimeZone:sourceTimeZone];

        NSString *dateRepresentation = [dateFormatter stringFromDate:dateFromString];
        //Log: dateRepresentation - 2016-03-08 01:00:00

        return dateRepresentation;
    }
    @catch (NSException *exception) {
        NSLog(@"Exception :%@", exception.debugDescription);
        return nil;
    }
}

在上面的代码//Log:中显示了定义变量的调试值。

我也检查isDayLightSavingTime但它永远不会执行。 (始终返回NO)。

此外,我无法在代码中将核心timeZone设置为DST,因为应用程序可能具有不同的时区。

无法弄清楚如何处理丢失的一小时。

最后一行:dateRepresentation显示错误的时间1 AM。它应该是2 AM

0 个答案:

没有答案
相关问题