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

查看:232
本文介绍了将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天全站免登陆