Search code examples
iostimezonensdatenstimezone

How to get timezone from time string


NSDate class doesn't store information about timezones. I have to store NSTimeZone separately. I can't find any way to get timezone from string like: "2015-01-09T00:00:00+02:00" or "2015-01-09T02:00:00Z . Could you help me please?


Solution

  • I suggest using library for formatting Date data format. I can recommend ISO8601 date formatter - https://github.com/boredzo/iso-8601-date-formatter and using it's [dateFormatter dateComponentsFromString: method to get NSDateComponents

    Edit:

    Just to include example with metioned library:

    ISO8601DateFormatter *dateFormatter = [[ISO8601DateFormatter alloc] init];
    dateFormatter.includeTime = YES;
    NSString *testTime = @"2015-01-09T00:00:00+02:00";
    NSTimeZone *timeZone;
    NSDateComponents *components = [dateFormatter dateComponentsFromString:testTime timeZone:&timeZone];
    

    Produces:

    Printing description of timeZone:
    GMT+0200 (GMT+2) offset 7200