2012-01-24 11 views
1

在某些情況下,我需要在1天內增加一個NSDate。對於它,我使用了dateByAddingTimeInterval,但它不起作用。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 %@",dayString, 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(不建議使用,我知道),但它不是工作壓力太大。哪裏不對?

問候!

回答

9

[endDate dateByAddingTimeInterval:dayinseconds];返回一個值,該值是函數產生的新日期。日期是不可變的對象(比如字符串),所以你不能修改它們 - 你只能通過應用一個函數來獲得一個新的日期。

如果你寫這一點,相反,它會工作:

endDate = [endDate dateByAddingTimeInterval:dayinseconds]; 
+0

這將是date30 = [現在dateByAddingTimeInterval :-(86400 * 30)];不加30天。現在假設=今天 –

+0

@atilla你是對的,原始問題中有一個以上的誤解,我只解決了其中的一個。 –

1

[endDate dateByAddingTimeInterval:dayinseconds];不改變現有的對象(結束日期),它返回一個新的NSDate對象,所以做

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