In my app I download some data as JSON
from an API
which contains an entry with local time:
"local_date" : "2015-07-08T13:18:14+02:00"
The JSON data are parsed into an NSDictionary* information
:
NSDateFormatter* dateFormatter= [NSDateFormatter new];
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
NSDate *date = [self.dateFormatter dateFromString:information[@"local_date"]];
The date
is now correctly set in UTC (which i need for some computations) but to display the local data in the user interface i need to display the date in the correct time zone.
My Question ist:
How can i extract the NSTimeZone
from my string? I am looking for something like NSTimeZone* timeZone = [NSTimeZone parseFromString:@"+02:00"];
I've read the documentation of NSDateFormatter, NSCalendar and NSTimeZone but didn't find out how to get the timezone from a string like mine.
Thanks in advance!
Again: when you say "in local time", you mean local to the returned string, not to the user? So I get sent a date from Germany, I have enough information both to turn it into an NSDate and so that I could create an NSDateFormatter
that recreated exactly the original string were that the output I wanted?
First of all: the time zone isn't actually in the string you supplied. It says +02:00 which tells you the offset from GMT. It doesn't tell you the time zone. E.g. an offset of +02:00 right now could be SAST, the South African time zone, could be EET, the Eastern European time zone, could be CAT, the Central African time zone, etc. There's therefore no direct way to map from offset to zone.
Supposing you just want to preserve the offset so that you can apply it later, luk2302's suggestion is probably in the right direction but I'd go the opposite way around (also I'd pay attention to QA1480):
NSString *time = @"2015-07-08T13:18:14+02:00"; // or whatever
NSDateFormatter *dateFormatter= [NSDateFormatter new];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZ";
NSDate *correctDate = [dateFormatter dateFromString:time];
NSDate *dateWithoutOffset = correctDate;
NSRange rangeOfPlus = [time rangeOfString:@"+"];
if(rangeOfPlus.location != NSNotFound)
{
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";
dateWithoutOffset = [dateFormatter dateFromString:[time substringToIndex:rangeOfPls.location]];
}
NSLog(@"Offset in date was %0.0f seconds", [dateWithoutOffset timeIntervalSinceDate:correctDate]);
Because you're doing something obtuse and unusual — normal apps deal only with fixed date format strings, with dates without time zones (as within NSDate
s), and with displaying things in the user's local time — you'll probably need to store and deal with the offsets manually.