سؤال

I want to convert a NSDate from one timezone to another.

Here is my code:

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;

}

In the output window, I can see this print out:

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

For some reason return [dupComponents date]; always return nil, even though I can clearly see in the debugger that it is properly initialised. It contains the values I expect.

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

Why it is the case?

هل كانت مفيدة؟

المحلول

I find out the solution.

I need to set a calendar object to NSDateCompoent object before calling date:

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

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

return [dupComponents date]; 
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top