微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ios – datebyAddingTimeInterval不起作用

在某些情况下,我需要在1天内增加一个NSDate.对于它,我使用dateByAddingTimeInterval,但它不起作用.

这是代码

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"dd/MM/yyyy HH:mm"];
Nsstring *startDate = [Nsstring stringWithFormat:@"%@/2012 %@",dayString,begin];
Nsstring *endStringForDate = [Nsstring stringWithFormat:@"%@/2012 %@",end];

NSLog(@"Csantos: event starts: %@,event ends: %@",startDate,endStringForDate);

NSDate *beginDate = [dateFormat dateFromString:startDate];
NSDate *endDate = [dateFormat dateFromString:endStringForDate];

NSComparisonResult result = [beginDate compare:endDate];


if(result == NSOrderedDescending){
    NSTimeInterval dayinseconds = 24 * 60 * 60;

    [endDate dateByAddingTimeInterval:dayinseconds];
    NSLog(@"Csantos: event ends: %@",endDate);
}

结果:

2012-01-24 12:09:47.837 app[3689:207] Csantos: event starts: 19/02/2012 23:00,event ends: 19/02/2012 03:00
2012-01-24 12:09:47.837 app[3689:207] Csantos: event ends: 19/02/2012 03:00

我已经尝试过addTimeInterval(不推荐使用,我知道),但它也没有用.怎么了?

问候!

解决方法

[endDate dateByAddingTimeInterval:dayinseconds];返回一个值,该值是函数生成的新日期.日期是不可变对象(如字符串),因此您无法修改它们 – 您只能通过应用函数获得新日期.

如果你写这个,相反,它会工作:

endDate = [endDate dateByAddingTimeInterval:dayinseconds];

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐