iOS将服务器时间转换为设备本地时间?

时间:2015-09-28 09:16:21

标签: ios objective-c datetime nsdateformatter

我遇到了将服务器时间(阿根廷)转换为设备本地时间的问题。 这是我目前的代码 -

    -(NSString *)getLocalTimeStringFrom:(NSString *)sourceTime
{
    static NSDateFormatter* df = nil;
    if (df == nil)
    {
        df = [[NSDateFormatter alloc]init];
    }
    df.dateFormat = @"HH:mm:ss";

    NSDate* d = [df dateFromString:sourceTime];
    NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:@"ART"];//America/Argentina/Buenos_Aires (GMT-3)
    NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone]; //Asia/Kolkata (IST)

    [df setTimeZone: sourceZone];
     NSLog(@"sourceZone time is %@" , [df stringFromDate: d]);
    [df setTimeZone: localTimeZone];
    NSLog(@"local time is %@" , [df stringFromDate: d]);

     NSLog(@"original time string was %@" , sourceTime);
    return [df stringFromDate: d];
}

如果sourceTime字符串为00:05:00

,则此处为日志
    2015-09-28 15:04:24.118 DeviceP[230:17733] sourceZone time is 15:35:00
2015-09-28 15:04:24.121 DeviceP[230:17733] local time is 00:05:00
2015-09-28 15:04:33.029 DeviceP[230:17733] original time string was 00:05:00

请注意,我的本地时间与我传入方法的时间字符串相同。我看了thisthis等各种SO帖子。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

由于您的时间字符串是ART,因此您应该在从字符串创建日期之前设置日期格式化程序的时区。手段如下

-(NSString *)getLocalTimeStringFrom:(NSString *)sourceTime
{
    static NSDateFormatter* df = nil;
    if (!df) {
        df = [[NSDateFormatter alloc]init];
        df.dateFormat = @"HH:mm:ss";
    }

    NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:@"ART"];
    [df setTimeZone: sourceZone];
    NSDate *ds = [df dateFromString:sourceTime];
    NSLog(@"sourceZone time is %@" , [df stringFromDate: ds]);

    NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
    [df setTimeZone: localTimeZone];
    NSLog(@"local time is %@" , [df stringFromDate: ds]);

    return [df stringFromDate: d];
}