NSDate 获取本地时间
NSDate get local time
我构建了从数据库获取日期字符串(法国时间日期)的应用程序。得到字符串后,我将其转换为 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];
进入self.date
我得到(如果我打印对象):
2016-06-10 21:00:00 +0000
但是当我尝试将其转换为当地时间时:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];
NSString *time = [formatter stringFromDate:cellItem.date];
我得到了不同的时间:00:00
知道问题出在哪里吗?
NSDateFormatter
的默认时区是设备的时区,由于您没有在第二个格式化程序中明确设置,因此将使用该时区。
为两个作业使用第一个格式化程序或像在第一个格式化程序中那样明确设置它:
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
另请注意:
Into self.date
i get (if i print the object)
如果您使用 NSLog()
或调试器查看 NSDate
对象,它将使用 [NSDate description]
生成字符串,该字符串将始终使用 GMT 时区。这总是让人绊倒。
我构建了从数据库获取日期字符串(法国时间日期)的应用程序。得到字符串后,我将其转换为 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];
进入self.date
我得到(如果我打印对象):
2016-06-10 21:00:00 +0000
但是当我尝试将其转换为当地时间时:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm"];
NSString *time = [formatter stringFromDate:cellItem.date];
我得到了不同的时间:00:00
知道问题出在哪里吗?
NSDateFormatter
的默认时区是设备的时区,由于您没有在第二个格式化程序中明确设置,因此将使用该时区。
为两个作业使用第一个格式化程序或像在第一个格式化程序中那样明确设置它:
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];
另请注意:
Into
self.date
i get (if i print the object)
如果您使用 NSLog()
或调试器查看 NSDate
对象,它将使用 [NSDate description]
生成字符串,该字符串将始终使用 GMT 时区。这总是让人绊倒。