Search code examples
objective-cnsdatensdateformatternsdatecomponentsnstimezone

I have a method that takes timezone name as a parameter and gives the current date's day component. But it gives different incorrect results


Suppose i have two parameters

Australia/Sydney (GMT+10) offset 36000 & Asia/Kolkata (IST) offset 19800

as timezones, it gives different values for the day component of current day itself. I am not able to figure out what am i doing wrong.. :( A little clue will be appreciated

-(NSInteger)getDayWithTimeZoneName:(NSString *)timeZoneName{

    // Instantiate a timezone
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:timeZoneName];

    //Instantiate a date formatter
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setLocale:[NSLocale currentLocale]];
    [df setTimeZone:timeZone];
    [df setDateFormat:@"yyyy-MM-dd"];

    NSString *dateStr = [df stringFromDate:[NSDate date]];
    NSDate *date = [df dateFromString:dateStr];
//    NSDateComponents *components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay fromDate:date];
    NSDateComponents *components = [[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar]components:NSDayCalendarUnit fromDate:date];
    NSInteger day = [components day];

    NSLog(@"Date component for timeZone %@ is %ld", timeZoneName,(long)day);
    return day;
}

Solution

  • NSFormatter isn't designed to convert or calculate dates:

    NSString *dateStr = [df stringFromDate:[NSDate date]];
    

    dateStr is the date in Sydney (2016-05-16 0:00).

    NSDate *date = [df dateFromString:dateStr];
    

    date is GMT, 10 hours behind Sydney (2016-05-15 14:00).

    Use NSCalendar to calculate dates:

    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.timeZone = timeZone;
    NSDateComponents *components = [calendar components:NSCalendarUnitDay fromDate:[NSDate date]];
    NSInteger day = [components day];