0

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

Atilla Jax
  • 615
  • 5
  • 15

1 Answers1

3

So given you have the three NSStrings: 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.

mbogh
  • 1,361
  • 11
  • 28
  • In addition, you might want to set the "locale" of the date formatter to "POSIX", to avoid dependencies on the user's regional preferences. Compare http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature. – Martin R Jan 20 '15 at 18:58
  • You should be able to use `ZZZZZ` instead of `Z` for the time offset, this parses `-HH:MM` - see [date formats](http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns). That avoids having to remove the `:`. – CRD Jan 20 '15 at 19:02
  • @CRD: Yes, support for ZZZZZ was added in iOS 6 and OS X 10.8. – Martin R Jan 20 '15 at 19:07