iOS:将UTC时区转换为设备本地时区 [英] iOS: convert UTC timezone to device local timezone

查看:372
本文介绍了iOS:将UTC时区转换为设备本地时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to convert the following timezone to device local timezone:

2013-08-03T05:38:39.590Z

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

Please let me know how to convert it to local timezone.

我该怎么做?

推荐答案

时区可以应用于NSDateFormatter ,您可以根据时差生成NSDate变量。

Time zones can be applied to NSDateFormatter, from which you can generate NSDate variables differentiated by the time difference.

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时区转换为设备本地时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆