Reputation: 615
I have a time zone formatted like this in an incoming string which I have no control over (it comes in a dictionary from server)
tzHours = NSString * @"+01:00"
But I need to convert it into a NSTimeZone
so I can format a date
NSString *date = [dateDictionary safeObjectForKey:@"date"];
NSString *time = [dateDictionary safeObjectForKey:@"time"];
NSString *tzHours = [dateDictionary safeObjectForKey:@"timeZone"];
// Format the date based off the timezone
NSDateFormatter *formatter = [self _apiDateFormatterWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
But I am unsure how to do this.
Is there a good way to do handle this?
Many thanks
Upvotes: 0
Views: 560
Reputation: 1361
So given you have the three NSString
s: date
, time
and tzHours
. You could do something like this:
NSString *date = @"2015-01-01";
NSString *time = @"14:00:01";
NSString *tzHours = @"+01:00";
NSString *dateString = [NSString stringWithFormat:@"%@ %@ %@", date, time, tzHours];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss ZZZZZ";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSDate *dateObject = [dateFormatter dateFromString:dateString];
The dateFormat
of the NSDateFormatter
naturally depends on the format of date
and time
.
Also remember to cache the NSDateFormatter
or else you will suffer performance-wise.
Upvotes: 3