2012-07-15 12 views
3

我得到當前的NSDate在用戶時間段用下面的代碼格式化的NSDate對象更改時區

-(NSDate *)getCurrentDateinLocalTimeZone 
{ 
NSDate* sourceDate = [NSDate date]; 

NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
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] ; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; 

return [dateFormatter dateFromString: [dateFormatter stringFromDate:destinationDate]]; 
} 

,並在我的應用程序的一些其他問題我要格式化的日期爲「HH:MM 「用於UI目的,所以我使用下面的方法

-(NSString *)formatDate:(NSDate *)date 
{ 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 
dateFormatter.dateFormat = @"HH:mm"; 
return [dateFormatter stringFromDate:date]; 
} 

如果第二方法的輸出由3個小時內從第一方法的結果偏移,,,我只要改變的NSDate的格式不時間,我做錯了什麼?

+0

請注意,第一個例程不格式化/打印日期。爲什麼在第一個例程中有最後一行?只需返回'destinationDate'。 – 2012-07-15 13:24:35

+0

我使用最後3行來格式化輸出 – ahmad 2012-07-15 13:31:22

+0

第一個例程中的最後一行將日期簡單地轉換爲char形式並返回到NSDate形式 - 一個無操作。 ***沒有***格式(或時區)存儲在NSDate對象中。 – 2012-07-15 13:45:58

回答

6

getCurrentDateinLocalTimeZone方法調整時區的日期,使用截斷時區的格式字符串對其進行格式化,並將格式化的字符串解析回來。由此產生的NSDate位於UTC時區(+0000,2012-07-15 16:28:23 +0000表示UTC時間)。 formatDate:方法使用爲當地時區設置的dateFormatter,產生不同的時間。您應設置格式使用UTC以獲取正確的時間:在formatDate:

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]]; 

更換

[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]]; 

+0

我試過了,它沒有工作......這裏是你的解決方案的輸出2012年3月15日16:28:23 +0000 //第一個方法的返回值 2012-07-15 16:28: 34.037鏈接測試Rassayl [20642:f803] 19:28 – ahmad 2012-07-15 13:29:56

+0

@ahmad我修復了答案,我認爲這應該會更好。 – dasblinkenlight 2012-07-15 13:44:37

+0

@ahmad - 第一個例程不是格式化日期,也不是調整時區。如果你NSLog它,你得到的NSDate對象將顯示UTC的時間。 – 2012-07-15 13:47:24