从NSString转换为NSDate时,日期会发生变化 [英] Date is getting changed while converting to NSDate from NSString

查看:148
本文介绍了从NSString转换为NSDate时,日期会发生变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NSDateFormatter的帮助下将NSString转换为NSDate。现在代码在所有操作系统和设备&模拟器,但它在英国,美国地区创建不同的输出。这是我正在使用的代码。

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];

实际日期是:2010-09-05 04:00:00

Actual date is : 2010-09-05 04:00:00

美国产量:2010-09-04 21:00:00 -0700

Output at USA : 2010-09-04 21:00:00 -0700

似乎问题出现在TimeZone / Locale的某个地方但是不知道解决方案。
我也尝试过:

It seems the problem is at TimeZone/Locale somewhere but don't know the solution. I also tried :

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

但无法解决问题。

是否有任何简单的方法可以从NSString获取NSDate,因为字符串实际上代表的不受TimeZone的影响。我只想获得NSDate,因为它出现在NSString中,日期和时间没有变化。时间。有什么办法吗?
提前致谢。

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.

推荐答案

这取决于您再次输出日期的方式。如果您使用的是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.

正确的用法是:

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];

NSString* finalDateString =  [dateFormatter stringFromDate:dateObj];
[dateFormatter release];

输出:

2010-09-05 04:00:00

我已经测试了这段代码几个时区。

I have tested this code in several time-zones.

这篇关于从NSString转换为NSDate时,日期会发生变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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