Search code examples
iosobjective-cnsdatensdateformatternstimezone

iOS - NSDate is not adding/subtracting Timezone difference right


i am trying to convert a date time that is in UTC format, to a different timezone

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"PKT"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *finalDate = [dateFormatter dateFromString:@"2015-08-18T23:00:00"];

PKT is UTC+05:00 the result should be 2015-08-19 04:00:00 +0000 instead it is subtracting and the result is 2015-08-18 18:00:00 +0000.

What i am doing wrong?


Solution

  • I still don't know what caused this to wrongly add/sub time. If I pass UTC+05:00 as a timezone abbreviation it subtracts and if I pass UTC-05:00 I adds up time. I found a workaround and solved this problem here is the code

    +(NSString*)getDBDate_UTC:(NSString*)date{
    
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    [formatter1 setCalendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierISO8601]];
    [formatter1 setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
    [formatter1 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    
    NSDate* sourceDate = [formatter1 dateFromString:date];
    
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC+05:00"];
    NSTimeZone* destinationTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    
    NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
    
    return [formatter1 stringFromDate:destinationDate];
    
    }
    

    Hope this helps