2015-09-28 185 views
0

我收到一些问题将服务器时间(阿根廷)转换为设备本地时间。 这里是我当前的代码 -iOS将服务器时间转换为设备本地时间?

-(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 

请注意,我让本地时间相同时间字符串我传递给方法。我看起来像各种SO后thisthis。 任何帮助,将不胜感激。

+0

为什么在每次调用此方法时创建新实例时将dateformatter声明为静态?在你问题是与时区。 – rckoenes

+0

,因为我在循环中调用此方法,并且不想每次重新创建时,我的约会对于所有迭代都是相同的。这是一个问题吗? – Bharat

+1

但是您每次都创建日期格式化程序。 – rckoenes

回答

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]; 
} 
相关问题