2014-02-19 90 views
0

我做了一個代碼來使用兩個不同的日期選擇器找到兩個日期之間的差異。我無法找到兩個日期之間的差異。兩個日期的差別總是爲零。如何通過使用兩個不同的日期選擇器找到兩個日期之間的差異

@property (strong, nonatomic) IBOutlet UILabel *date1; 
@property (strong, nonatomic) IBOutlet UILabel *date2; 
- (IBAction)cale1:(id)sender; 
- (IBAction)cale2:(id)sender; 
@property (strong, nonatomic) IBOutlet UIDatePicker *datePicker1; 
@property (strong, nonatomic) IBOutlet UIDatePicker *datePicker2; 
@property NSDate *d1,*d2; 

@implementation ViewController 

- (IBAction)cale1:(id)sender { 
    NSDateFormatter *dc=[[NSDateFormatter alloc]init]; 
    dc.dateStyle=NSDateFormatterFullStyle; 
    _d1=_datePicker1.date; 
    _date1.text=[dc stringFromDate:_datePicker1.date]; 
    NSLog(@"Date %@",_date1); 
} 

- (IBAction)cale2:(id)sender { 
    NSDateFormatter *dc=[[NSDateFormatter alloc]init]; 
    dc.dateStyle=NSDateFormatterFullStyle; 
    _d2=_datePicker2.date; 
    _date2.text=[dc stringFromDate:_datePicker2.date]; 
    NSLog(@"Date %@",_d2); 

    [self isSameDay:_d1 otherDay:_d2]; 

} 
-(BOOL)isSameDay:(NSDate *)date1 otherDay:(NSDate *)date2{ 
    NSCalendar *cale=[NSCalendar currentCalendar]; 
    unsigned unitFlags=NSYearCalendarUnit| NSMonthCalendarUnit| NSDayCalendarUnit; 
    NSDateComponents *comp1=[cale components:unitFlags fromDate:date1]; 
    NSDateComponents *comp2=[cale components:unitFlags fromDate:date2]; 


    // NSString *comp=[NSString stringWithFormat:@"%d", [comp1 day]==[comp2 day]&&[comp1 month]==[comp2 month]&&[comp1 year]==[comp2 year]]; 
    BOOL a=[comp1 day]==[comp2 day]&&[comp1 month]==[comp2 month]&&[comp1 year]==[comp2 year]; 

    NSLog(@"Date Differ%hhd",a); 
    return a; 
} 
+0

閱讀此項。 [NSCalendar類參考](https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html)。向下滾動到'components:fromDate:toDate:options:' – Desdenova

回答

0

比較方法有效日期中的日期是?

如果他們是你可以這樣做:如果日期是不一樣的

BOOL difference = [date1 timeIntervalSinceDate:date2] > 0; 

差異將是真實的。 timeIntervalSinceDate返回NSTimeInterval這是:

用於指定時間間隔,以秒爲單位。

+0

我希望在數字上有所不同。如果它從第一個日期到結束日期有4天差異。我需要的結果是4. – MAHBOOB

+1

那不是你的代碼試圖做什麼.. – CW0007007

+0

如何使上面的代碼適用於我問過的問題。 – MAHBOOB

0

爲了比較兩個日期,你需要使用NSDateComponents.I修改你的函數「isSameDay」。它返回兩個日期之間的日差數。

-(int)isSameDay:(NSDate *)date1 otherDay:(NSDate *)date2 
{  
    NSDateComponents *components; 

    int days; 

    components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit 
              fromDate: date1 toDate: date2 options: 0]; 
    days = (int) [components day]; 

    NSLog(@"days %d",abs(days)); 

    return days; 

} 
+0

您的方法簽名和方法主體不匹配 – Marc

+0

我忘記指定更改調用「isSameDay」方法。請按以下方式致電。 ind numberofdifference = [self isSameDay:_d1 otherDay:_d2];請更改方法名稱,以便它更具可讀性(如果需要)。 –