简体   繁体   English

NSDate获取本地时间

[英]NSDate get local time

I build app that get date string(date in french time) from a database. 我建立从数据库获取日期字符串(法国时间的日期)的应用程序。 after i get the string i convert it to nsdate: 我得到字符串后,将其转换为nsdate:

NSString *dateStr = "20/3/2016 21:00 +0000";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm zzz"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
self.date = [dateFormatter dateFromString:dateStr];

Into self.date i get(if i print the object) : 进入self.date我得到(如果我打印对象):

2016-06-10 21:00:00 +0000

But when i try to convert it to local time: 但是当我尝试将其转换为本地时间时:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];
NSString *time = [formatter stringFromDate:cellItem.date];

I get a different time: 00:00 我得到了另一个时间: 00:00 : 00:00

Any idea what can be the problem? 知道可能是什么问题吗?

The default time zone for an NSDateFormatter is the time zone of the device, and as you didn't set it explicitly in the second formatter, that is what will be used. NSDateFormatter的默认时区是设备的时区,并且由于您没有在第二个格式化程序中显式设置它,因此将使用该时区。

Use the first formatter for both jobs or set it explicitly as you did in the first formatter: 将第一个格式化程序用于这两个作业,或者像在第一个格式化程序中那样显式设置它:

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];

Also a note on: 还要注意:

Into self.date i get (if i print the object) 进入self.date我得到(如果我打印对象)

If you are using NSLog() or the debugger to view an NSDate object, it will use [NSDate description] to generate the string, which will always use the GMT time zone. 如果使用NSLog()或调试器查看NSDate对象,它将使用[NSDate description]生成字符串,该字符串将始终使用GMT时区。 This constantly trips people up. 这经常使人们绊倒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM