iOS:将UTC时区转换为设备本地时区

5

我正在尝试将以下时区转换为设备本地时区:

2013-08-03T05:38:39.590Z

请告诉我如何将其转换为本地时区。

我该怎么做?


可能是如何将时间转换为iPhone设备的时区?的重复问题。 - Lennart Regebro
2个回答

11

时间区域可以应用于NSDateFormatter,通过它你可以生成根据时间差异有所不同的NSDate变量。

NSString* input = @"2013-08-03T05:38:39.590Z";
NSString* format = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

// Set up an NSDateFormatter for UTC time zone
NSDateFormatter* formatterUtc = [[NSDateFormatter alloc] init];
[formatterUtc setDateFormat:format];
[formatterUtc setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

// Cast the input string to NSDate
NSDate* utcDate = [formatterUtc dateFromString:input];

// Set up an NSDateFormatter for the device's local time zone
NSDateFormatter* formatterLocal = [[NSDateFormatter alloc] init];
[formatterLocal setDateFormat:format];
[formatterLocal setTimeZone:[NSTimeZone localTimeZone]];

// Create local NSDate with time zone difference
NSDate* localDate = [formatterUtc dateFromString:[formatterLocal stringFromDate:utcDate]];

NSLog(@"utc:   %@", utcDate);
NSLog(@"local: %@", localDate);

[formatterUtc release];
[formatterLocal release];

2

尝试像这样:

   NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
   [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
   [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
   NSDate* utcTime = [dateFormatter dateFromString:@"2013-08-03T05:38:39.590Z"];
   NSLog(@"UTC time: %@", utcTime);

   [dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
   [dateFormatter setDateFormat:@"M/d/yy 'at' h:mma"];
   NSString* localTime = [dateFormatter stringFromDate:utcTime];
   NSLog(@"localTime:%@", localTime);  

希望这能对您有所帮助...


是的,成功了。非常感谢,伙计。 - Kunal Gupta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接