从 NSString 转换为 NSDate 时日期发生变化
我正在 NSDateFormatter 的帮助下将 NSString 转换为 NSDate。现在,代码在所有带有设备和设备的操作系统中都可以正常工作。模拟器,但它在英国、美国地区创建不同的输出。这是我正在使用的代码。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateString=[NSString stringWithString:@"2010-09-05 04:00:00"];
NSDate *dateObj = [dateFormatter dateFromString:dateString];
实际日期是:2010-09-05 04:00:00
美国输出:2010-09-04 21:00:00 -0700
问题似乎出在时区/区域设置某处,但不知道解决方案。 我也尝试过:
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
但无法摆脱这个问题。
是否有任何简单的方法可以从 NSString 获取 NSDate 作为字符串实际表示的内容,而不受 TimeZone 的影响。我只想获得 NSDate,因为它出现在 NSString 中,并且日期和日期没有变化。时间。有什么办法吗? 提前致谢。
I am converting NSString to NSDate with help of NSDateFormatter. Now code works fine here in all OS with device & simulator but it is creating different Output at UK, USA region. Here is the code that I am using.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *dateString=[NSString stringWithString:@"2010-09-05 04:00:00"];
NSDate *dateObj = [dateFormatter dateFromString:dateString];
Actual date is : 2010-09-05 04:00:00
Output at USA : 2010-09-04 21:00:00 -0700
It seems the problem is at TimeZone/Locale somewhere but don't know the solution.
I also tried :
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
but couldn't get out of the issue.
Is there any simple way to get NSDate from NSString as the string actually represents without getting affected by TimeZone. I just want to get NSDate as it appears in NSString with No change in date & time. Is there any way?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于您如何再次输出日期。如果您使用 NSDateFormatter,您将得到相同的结果。如果您只是通过调用
[日期描述]
来输出日期,则输出会有所不同,因为包含有关本地时区的信息。正确的用法是:
输出:
我已经在多个时区测试了此代码。
It depends on how you are outputting the date again. If you are using the NSDateFormatter, you will get the same result. If you are just outputting the date by calling
[date description]
the output will differ since information about the local time zone are included.A correct usage would be:
Output:
I have tested this code in several time-zones.