Search code examples
iosobjective-cnsdatedstnsdatecomponents

Handling Day light time difference


As per our application specification, we need to schedule call for conference, while I scheduling I have been facing problem with Day light time difference.

This is the case: US day light time changes on Nov 3 this year, when I schedule a call for eg: 5 P.M on Nov 4, that time I am converting into GMT and send to server. If I convert that GMT time its giving 4 P.M Nov 4, instead of 5 P.M. Even though its correct only, however as per user perspective he scheduled for 5 P.M not 4 P.M, so how to handle this case.

I'm converting into GMT like ...

- (NSDateComponents*) convert_to_gmt_time : (NSDate*) date
{
    NSDate *localDate = date;
    NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
    NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] - timeZoneOffset;
    NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];

    NSDateComponents *date_comp = [[NSCalendar currentCalendar] components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:gmtDate];

    return date_comp;
}

Edit:

This is how I'm coverting GMT time to local...

  NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM dd, yyyy"];
NSDate *strt_date_loc = [gregorian dateFromComponents:start_date]; // start_date i'm filling after received from server as GMT.

    // Get date string.
    NSString *strt_date = [dateFormatter stringFromDate: strt_date_loc];

Any help is really appreciated. Thanx.


Solution

  • Got the problem,

    Problem was with GMT conversion, as I did consider the current time difference to GMT, and not the time difference that is in effect at the date to be converted.

    This is how I fixed...

    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSDateComponents *date_comp = [cal components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:localDate];