2014-02-15 33 views
3

我想將NSDate從一個時區轉換爲另一個時區。NSTime:爲什麼[NSDateComponent date]在這裏返回零?

這裏是我的代碼:

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];總是返回零,即使我可以清楚地看到調試器已正確初始化。它包含我期望的值。

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

'[[NSCalendar currentCalendar]拷貝]'拷貝是不必要的。另外你爲什麼使用「C」函數而不是ObjectiveC方法? – zaph

+0

@Zaph時區更改只是暫時的和本地的。我不想更改'currentCalendar'。 –

+1

'[NSCalendar currentCalendar]'創建一個新的日曆,所以這是創建一個新的日曆,然後製作一個新日曆的副本,然後釋放新日曆。它真的支付學習Objective-C內存管理。 – zaph

回答

17

我找出解決方案。

我需要調用date之前設置日曆對象到對象NSDateCompoent:

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

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

return [dupComponents date]; 
相關問題