开发者

Date is getting changed while converting to NSDate from NSString

开发者 https://www.devze.com 2023-01-17 17:29 出处:网络
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

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 0开发者_StackOverflow中文版4: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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号