iPhone:NSDate将GMT转换为当地时间

时间:2010-10-10 18:03:12

标签: iphone objective-c localization nsdate

我目前有一个API调用,以格式:2010-10-10T07:54:01.878926

返回日期/时间

我可以假设这是GMT吗?我还将其转换为NSDate对象。有没有办法使用本地iPhone时间重新计算时间?

4 个答案:

答案 0 :(得分: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];

答案 1 :(得分:19)

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

答案 2 :(得分: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];

答案 3 :(得分:-2)

NSDate *now = [NSDate date];
NSLog(@"%@", [now dateWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" 
              timeZone:[NSTimeZone timeZoneWithName:@"GMT"]]);