0
votes

I have the following date as a string: 2015-04-18T08:35:00.000+03:00 and I would like to get an offset from the GMT in seconds, i.e. 10800.

I can split the date string by '+' character, have a string xy:ab and then calculate the offset with formula xy*3600 + a*60 + b.

Is there any better way to achieve what I need, for example using NSDate and NSDateFormatter?

1
Use NSDateFormatter.Droppy
That's a good point but the problem is that I don't know how. I can create a NSDateFormatter instance and set the date format yyyy-MM-dd'T'HH:mm:ss.SSSZ. But how can I get the number I want then?Merlin

1 Answers

2
votes

I've finally ended up using this code:

    NSString *dateStringWithTZ = @"2015-04-18T08:35:00.000+03:00";

    // Create date object using the timezone from the input string.
    NSDateFormatter *dateFormatterWithTZ = [[NSDateFormatter alloc] init];
    dateFormatterWithTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
    NSDate *dateWithTZ = [dateFormatterWithTZ dateFromString:dateStringWithTZ];

    // Cut off the timezone and create date object using GMT timezone.
    NSString *dateStringWithoutTZ = [dateStringWithTZ substringWithRange:NSMakeRange(0, 23)];
    NSDateFormatter *dateFormatterWithoutTZ = [[NSDateFormatter alloc] init];
    dateFormatterWithoutTZ.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS";
    dateFormatterWithoutTZ.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSDate *dateWithoutTZ = [dateFormatterWithoutTZ dateFromString:dateStringWithoutTZ];

    // Calculate the difference.
    NSInteger difference = [dateWithoutTZ timeIntervalSinceReferenceDate] - [dateWithTZ timeIntervalSinceReferenceDate];
    return [NSNumber numberWithInteger:difference];