将 GMT NSDate 转换为设备的当前时区 [英] Convert GMT NSDate to device's current Time Zone

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

问题描述

我使用 Parse.com 来存储一些值:

I'm using Parse.com to store some values:

这些是 GMT 值.如何将这些转换为设备的当前时区并获得 NSDate 结果?

These are GMT values. How do I convert these to the device's current time zone and get NSDate as a result?

推荐答案

NSDate 始终以 GMT 表示.只是你表达它的方式可能会改变.

NSDate is always represented in GMT. It's just how you represent it that may change.

如果要将日期打印到 label.text,则使用 NSDateFormatter[NSTimeZone localTimeZone] 将其转换为字符串,如下:

If you want to print the date to label.text, then convert it to a string using NSDateFormatter and [NSTimeZone localTimeZone], as follows:

NSString *gmtDateString = @"08/12/2013 21:01";

NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"dd/MM/yyyy HH:mm"];

//Create the date assuming the given string is in GMT
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *date = [df dateFromString:gmtDateString];

//Create a date string in the local timezone
df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];
NSString *localDateString = [df stringFromDate:date];
NSLog(@"date = %@", localDateString);

// My local timezone is: Europe/London (GMT+01:00) offset 3600 (Daylight)
// prints out: date = 08/12/2013 22:01

这篇关于将 GMT NSDate 转换为设备的当前时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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