gpt4 book ai didi

objective-c - NSTime : Why [NSDateComponent date] returns nil here?

转载 作者:太空狗 更新时间:2023-10-30 03:46:37 25 4
gpt4 key购买 nike

我想将 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

为什么会这样?

最佳答案

我找到了解决方案。

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

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

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

return [dupComponents date];

关于objective-c - NSTime : Why [NSDateComponent date] returns nil here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21791806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com