2011-08-24 102 views
1

我的應用程序從遠程服務器獲取日期/時間,該日期/時間總是在GMT + 1(UTC/GMT + 1小時)時區內。日期/時間轉換爲用戶的本地時間 - 問題

服務器提供的格式是:

24 08 2011下午8點45分

我想這個時間戳轉換爲用戶時區的等效時間/日期(用戶可以在世界任何地方)。

從而作爲一個例子: 24 08 2011下午8點45來自服務器應提交

24 08 2011下午9點45分對意大利用戶(羅馬)(GMT + 1)

這代碼適用於一些時區,但我有一種不好的感覺,有一些非常錯誤的它,並且有一個更優雅的方式來做到這一點

NSString *dateString = @"24 08 2011 09:45PM"; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"dd MM yyyy hh:mma"]; 
    NSDate *dateFromString = [[[NSDate alloc] init] autorelease]; 
    dateFromString = [dateFormatter dateFromString:dateString]; 


    NSDate* sourceDate = dateFromString; 
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"]; 
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone]; 
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate]; 
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate]; 
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset; 
    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ; 
    NSString *thePubDate = [dateFormatter stringFromDate:destinationDate];//[appLogic getPubDate]; 
    NSLog(@"Result : %@",thePubDate); 
    [dateFormatter release]; 
    //[dateFromString release]; 
    [destinationDate release]; 

我會感謝對此事

您的想法和建議

回答

4

只需設置時區的dateFormatter,這個代碼就足夠了

NSString *dateString = @"24 08 2011 09:45PM"; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"]; 
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"]; 
[dateFormatter setTimeZone:sourceTimeZone]; 
NSDate *dateFromString = [dateFormatter dateFromString:dateString]; 

的dateFromString現在將有日期24 08 2011下午8點45(北京時間)。然後將其轉換爲字符串當地時間剛代碼如下,

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd MM yyyy hh:mma"]; 
NSString *stringFromDAte = [dateFormatter stringFromDate:dateString]; 
+0

上述工作,但它會更清晰,如果兩個示例代碼集一起工作,你有重複的變量名稱和一些變量名稱不匹配。 –

相關問題