2010-10-10 136 views

回答

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

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
[dateFormatter setTimeZone:gmt]; 
NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]]; 
[dateFormatter release]; 
+0

的作品就像一个魅力...谢谢! :) – unicornherder 2010-10-10 18:45:19

+5

这是如何将GMT转换为当地时间?我相信它正在做相反的事情,并将本地转换为GMT? – willhblackburn 2015-01-20 15:08:59

1
NSDate *sourceDate = [NSDate dateWithTimeIntervalSince1970:gmtTimestamp]; 
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone]; 
NSInteger sourceGMTOffset = [destinationTimeZone secondsFromGMTForDate:0]; 
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate]; 
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset; 
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm"; 
[dateFormatter setTimeZone:destinationTimeZone]; 
NSString *localTimeString = [dateFormatter stringFromDate:destinationDate]; 
-2
NSDate *now = [NSDate date]; 
NSLog(@"%@", [now dateWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" 
       timeZone:[NSTimeZone timeZoneWithName:@"GMT"]]); 
+0

消息' - (NSString *)dateWithCalendarFormat:timezone:'在Apple的文档中不存在。 – 2013-01-18 19:09:02

+0

这给出了一个错误..你测试它吗? – 2013-05-10 04:38:26

17
NSDate* localDateTime = [NSDate dateWithTimeInterval:[[NSTimeZone systemTimeZone] secondsFromGMT] sinceDate:pubDate]; 
+0

太棒了。它解决了我的问题 – 2014-08-05 13:30:48

+0

** Swift **:'let localDate = NSDate(timeInterval:NSTimeInterval(NSTimeZone.systemTimeZone()。secondsFromGMT),sinceDate:date)' – Husam 2016-04-06 19:33:32