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

时间:2016-05-16 08:15:13

标签: objective-c nsdate nsdateformatter nsdatecomponents nstimezone

假设我有两个参数

澳大利亚/悉尼(GMT + 10)抵消36000& 亚洲/加尔各答(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;
}

1 个答案:

答案 0 :(得分:0)

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

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

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

NSDate *date = [df dateFromString:dateStr];

date是GMT,比悉尼落后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];