我正在尝试将以下时区转换为设备本地时区:
2013-08-03T05:38:39.590Z
请告诉我如何将其转换为本地时区。
我该怎么做?
最佳答案
时区可以应用于 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];
关于iOS:将 UTC 时区转换为设备本地时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18030078/