【问题标题】:iOS: convert UTC timezone to device local timezoneiOS:将 UTC 时区转换为设备本地时区
【发布时间】:2013-08-04 12:03:26
【问题描述】:

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

2013-08-03T05:38:39.590Z

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

我该怎么做?

【问题讨论】:

标签: ios objective-c timezone


【解决方案1】:

时区可以应用于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);  
    

    希望对你有帮助....

    【讨论】:

    • 是的,确实如此。非常感谢朋友
    猜你喜欢
    • 2010-11-19
    • 1970-01-01
    • 2014-08-12
    • 2011-09-16
    • 2019-05-31
    • 1970-01-01
    • 2014-08-18
    • 2014-10-05
    • 1970-01-01
    相关资源
    最近更新 更多