我有一个方法将时区名称作为参数并给出当前日期的日期部分。但它给出了不同的错误结果

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

假设我有两个参数

Australia/Sydney (GMT+10) 偏移量 36000 & Asia/Kolkata (IST) 偏移量 19800

作为时区,它为当天本身的日期部分提供了不同的值。我无法弄清楚我做错了什么.. :( 一点线索将不胜感激

-(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;
}

NSFormatter 不是为转换或计算日期而设计的:

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

dateStr 是悉尼的日期 (2016-05-16 0:00)。

NSDate *date = [df dateFromString:dateStr];

date 是格林威治标准时间,比悉尼晚 10 小时 (2016-05-15 14:00)。

使用 NSCalendar 计算日期:

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