Date is getting changed while converting to NSDate from NSString

一曲冷凌霜 提交于 2019-12-22 00:09:34

问题


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.


回答1:


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:

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

Output:

2010-09-05 04:00:00

I have tested this code in several time-zones.



来源:https://stackoverflow.com/questions/3812137/date-is-getting-changed-while-converting-to-nsdate-from-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!