2013-07-29 42 views
0

這是我的代碼,它完美地返回兩個日期之間的天數和月數。我想驗證這一點,因爲兩個日期之間的差異應該是一年。如果你選擇2013年7月29日作爲開始日期和2014年7月30日作爲結束日期,它不應該被允許執行more.please幫助提前感謝。找到兩個日期之間的差異正好是1年

NSString *sta = txtStartdate.text; // This is the start date 

    NSString *en = txtEnddate.text; //this is end date 

    NSDateFormatter *f = [[NSDateFormatter alloc] init]; 

    [f setDateFormat:@"dd/MM/yyyy"]; 

    NSDate *startDat = [f dateFromString:sta]; 

    NSDate *endDat = [f dateFromString:en]; 

    [f release]; 

    NSCalendar *gregorian = [[NSCalendar alloc] 
          initWithCalendarIdentifier:NSGregorianCalendar]; 

    NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit ; 

    NSDateComponents *components = [gregorian components:unitFlags 
               fromDate:startDat 
                toDate:endDat options:0]; 
    NSInteger months = [components month]; 
    NSInteger days = [components day]; 
    NSInteger years = [components year]; 

    NSLog(@"Number of months %d",months); 

    NSLog(@"Number of days %d",days); 

    NSLog(@"Number of years %d",years); 

    [gregorian release]; 

    if(years < 1)// This code works fine...i've edited it.. @wain helped 
    { 
     // 

}

+1

你可以比較兩個的NSDate就像郵局解釋說: 你爲什麼不使用一年日期組件http://stackoverflow.com/a/6112171/1343969 – Oyashiro

+0

? – Wain

+0

@Wain我怎樣才能修改代碼與年日期co​​mponent.sorry我是新的iphone – arshad

回答

1

添加NSYearCalendarUnitunitFlags,那麼當你獲得了components您可以要求year。這將處理閏年,比你試圖計算幾個月和幾天或計算結束日期(除非你使用組件來添加一年的日期來獲得結束日期)。

+0

是啊..它的工作..我已經添加NSYearCalendarUnit到unitFlags和reqstd年在compnents ..我已經更新上面的代碼..感謝很多.. @ wain – arshad