加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – NSTime:为什么[NSDateComponent date]在这里返

发布时间:2020-12-16 10:44:05 所属栏目:百科 来源:网络整理
导读:我想将NSDate从一个时区转换为另一个时区. 这是我的代码: NSDate* convertTime(NSDate* fromDate,NSTimeZone* fromTimeZone,NSTimeZone* toTimeZone) { if (fromTimeZone == toTimeZone) { return fromDate; } NSCalendarUnit val = NSCalendarUnitYear| NS
我想将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)

由于某种原因返回[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];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读