Date is getting changed while converting to NSDate

2019-04-14 19:28发布

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条回答
Animai°情兽
2楼-- · 2019-04-14 20:12

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.

查看更多
登录 后发表回答