NSTime:为什么[NSDateComponent date]在这里返回nil?

时间:2014-02-15 00:24:38

标签: objective-c nsdate nsdatecomponents nstimezone

我想将NSDate从一个时区转换为另一个时区。

这是我的代码:

NSDate* convertTime(NSDate* fromDate, NSTimeZone* fromTimeZone, NSTimeZone* toTimeZone) {
    if (fromTimeZone == toTimeZone) {
        return fromDate;
    }

    NSCalendarUnit val = NSCalendarUnitYear| NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour| NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitTimeZone;
    NSCalendar* dupCal =  [[NSCalendar currentCalendar] copy];

    [dupCal setTimeZone:toTimeZone];
    NSDateComponents *dupComponents = [dupCal components:val fromDate:fromDate];

    return [dupComponents date]; // <- Why return nil?

}

int testTimeZone() {
    NSDate* res = convertTime([NSDate date], [NSTimeZone defaultTimeZone], [NSTimeZone timeZoneWithName:@"America/New_York"]);
    NSLog(@"convertTime: %@", res);
    return 0;

}

在输出窗口中,我可以看到此打印输出:

2014-02-15 11:15:18.040 MyApp[28742:70b] convertTime: (null)

由于某些原因,return [dupComponents date];总是返回nil,即使我可以在调试器中清楚地看到它已正确初始化。它包含我期望的值。

Printing description of dupComponents:
<NSDateComponents: 0x100112260>
    TimeZone: America/New_York (EST) offset -18000
    Calendar Year: 2014
    Month: 2
    Leap month: no
    Day: 14
    Hour: 19
    Minute: 19
    Second: 29

为什么会这样?

1 个答案:

答案 0 :(得分:19)

我找到了解决方案。

我需要在调用date之前将日历对象设置为NSDateCompoent对象:

NSDateComponents *dupComponents = [dupCal components:val fromDate:fromDate];

[dupComponents setCalendar:dupCal]; // THIS IS THE SOLUTION

return [dupComponents date];