2013-08-06 62 views
5

我正在嘗試製作一個標籤,指出要等到事件還有多少天。我想計算今天的日期和事件日期之間的差異。我使用這個代碼,它給我-4600。它工作正常,直到我使用今天的日期。如何獲取兩個日期之間的天數objective-c

NSDateFormatter *f = [[NSDateFormatter alloc] init]; 
    [f setDateFormat:@"yyyy-MM-dd"]; 
    NSDate *startDate = [NSDate date]; 
    NSDate *endDate = [f dateFromString:end]; 
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit 
                 fromDate:startDate 
                  toDate:endDate 
                 options:0]; 
    return components.day; 
return components.day; 
+0

你說的一個問題是重複的我已經使用了這個答案,它不起作用。 – user1898829

+0

您是否確認'NSDate * endDate = [f dateFromString:end]'返回預期日期? - 字符串「end」包含什麼? –

+1

@ user1898829那麼你應該在你的問題中提到 – borrrden

回答

17

默認情況下[NSDate date]歸期像2013-08-06 08:50:25 +0000 並已設置你的格式化程序yyyy-MM-dd這一點,所以你有你的startDate轉換爲yyyy-MM-dd這種形式..

試試這個

NSDateFormatter *f = [[NSDateFormatter alloc] init]; 
    [f setDateFormat:@"yyyy-MM-ddHH:mm:ss ZZZ"]; 
    NSDate *startDate = [NSDate date]; 
    NSLog(@"%@",startDate); 
    NSDate *endDate = [f dateFromString:end]; 
    NSLog(@"%@",endDate); 


    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit 
                 fromDate:startDate 
                  toDate:endDate 
                 options:0]; 
    return components.day; 
相關問題