我得到當前的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的格式不時間,我做錯了什麼?
請注意,第一個例程不格式化/打印日期。爲什麼在第一個例程中有最後一行?只需返回'destinationDate'。 – 2012-07-15 13:24:35
我使用最後3行來格式化輸出 – ahmad 2012-07-15 13:31:22
第一個例程中的最後一行將日期簡單地轉換爲char形式並返回到NSDate形式 - 一個無操作。 ***沒有***格式(或時區)存儲在NSDate對象中。 – 2012-07-15 13:45:58