NSDateFormatter给我4小时的时间 [英] NSDateFormatter giving me time 4 hours ahead

查看:97
本文介绍了NSDateFormatter给我4小时的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个字符串Jun 11,2012 9:30 PM转换为NSDate,由于某种原因我提前4小时。有趣的是,我正在使用相同的字符串在详细视图中提供UIDatePicker,我必须进行相同的转换,并且UIDatePicker将时间渲染得很好。只有当我现在尝试在我的主要和详细视图中对其进行NSLog时,我才会遇到问题。

I'm converting a string "Jun 11, 2012 9:30 PM" to an NSDate and I keep getting 4 hours ahead for some reason. The funny thing is I'm using this same string to feed a UIDatePicker in a detailed view where I have to do the same conversion, and the UIDatePicker renders the time fine. Only when I now try to NSLog it in my main and detailed view do I have problems.

这在我看来:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM dd, yyyy h:mma"];  
NSDate *dateFromString = [[[NSDate alloc] init]autorelease];

NSLog(@"DATE %@", _date);

dateFromString = [formatter dateFromString:_date];

NSLog(@"NSDATEFROMSTRING %@", dateFromString);

NSLog返回:

2012-06-11 00:02:09.136 LocalDeals[78090:207] DATE Jun 11, 2012 9:30 PM
2012-06-11 00:02:09.137 LocalDeals[78090:207] NSDATEFROMSTRING 2012-06-12 01:30:00 +0000

即使我添加:

[formatter setTimeZone:[NSTimeZone defaultTimeZone]];

我在任何时候都会得到相同的结果。有任何想法吗?顺便说一句,这是在模拟器上,是的,我的区域格式设置为美国。

I still get the same results from any time I choose. Any ideas? This is on the simulator by the way and yes my Region Format is set to United States.

推荐答案

当您NSLog NSDate时将时间打印为GMT时区
为了查看正确的数据,您必须使用 stringFromDate

When you NSLog an NSDate it will print the time as a GMT time zone In order to see the correct data you will have to convert the NSDate to string using stringFromDate

NSDate *dateFromString = [[[NSDate alloc] init]autorelease];

NSLog(@"DATE %@", _date);

//Instead of nslog directly, use this stringFromDate:remindOn
NSString *str = [formatter stringFromDate:dateFromString];
NSLog(@"date is %@", str); //This will log the correct data

您遇到的问题不在NSDate中,但它是在记录它
更新为了将数据保存到文件或数据库,我建议您像这样保存

The problem you are getting is not in the NSDate but it is in Logging it UPDATE In order to save the data to a file or database i would suggest that you save it like this

NSTimeInterval timeInterval  = [dateFromString timeIntervalSince1970];

现在,当您从数据库中再次阅读时,您将会这样做

Now when you read it again from the database you would do

NSDate *data = [[NSDate alloc] initWithTimeIntervalSince1970:timeInterval]

这篇关于NSDateFormatter给我4小时的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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