puja puja - 1 month ago 15
iOS Question

NSString Date to NSDate

NSString Date
to
NSDate
in
iOS
not displaying proper details.
I have
NSString date
is :

NSString *strFinal = @"2016-10-20 12:00:00";


I am following below method to convert NSString to NSDate

NSString *strFinal = @"2016-10-20 12:00:00";


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

// [dateFormatter setDateFormat:@"yyyy-mm-dd hh:mm:ss"];

[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

NSDate *dateFromString = [[NSDate alloc] init];

dateFromString = [dateFormatter dateFromString:strFinal];


and my out put is :


string date is : 2016-10-20 12:00:00

NSDate is: 2016-10-19 18:30:00
+0000


it generates different date and different format from
NSString
i want the same
NSDate
.

Any help will be appreciated.
Thanks

Answer

You have problems with time zone and it can be solved by adding this line of code:

[dateformatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

You can also set TimeZone by:

[dateformatter setTimeZone:[NSTimeZone systemTimeZone]];

OR

[dateformatter setTimeZone:[NSTimeZone localTimeZone]];

OR

[dateformatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];