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];

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...