如何使用两个不同的日期选择器找到两个日期之间的差异

时间:2014-02-19 09:13:48

标签: ios objective-c uidatepicker

我做了一个代码,使用两个不同的日期选择器找到两个日期之间的差异。我找不到两个日期之间的区别。两个日期的差异始终为零。

@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;
}

2 个答案:

答案 0 :(得分:0)

比较方法中的日期是否有效?

如果是,你可以这样做:

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

如果日期不同,差异将成立。 timeIntervalSinceDate返回NSTimeInterval,即:

  

用于指定时间间隔,以秒为单位。

答案 1 :(得分: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;

}