I have a date string in this format: 2022-09-07T11:11:16+0300 and I want to convert it to NSDate and back again to NSString, I use this code:
NSString * dateCreatedString = @"2022-09-07T11:11:16+0300";
self.dateFormat = [[NSDateFormatter alloc] init];
[self.dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate * date = [self.dateFormat dateFromString:dateCreatedString];
.
.
.
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
formatter2.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSSZ";
NSString * newStr = [formatter2 stringFromDate:date];
And i get this string date: 2022-09-07 04:11:16.000-0400 instead of: 2022-09-07 11:11:16.000+0300.
Any idea what can be the problem?
Just specify the
timeZonefor your formatter (by default it refers to the system time zone when forming a string out of anNSDate):EDIT
If you want to preserve original time zone of the date string, i'm not aware of a simple way of doing so. You will have to parse the string manually and extract this information somehow. Here is how I would implement such a functions:
In the client code: