2015-09-28 184 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]; 
} 
相關問題