arshad
arshad

Reputation: 275

Find difference between two dates is exactly 1 year

This is my code and it perfectly returns number of days and months between two dates. i want to validate this like the difference between two dates should be exactly one year.like if u select july 29 2013 as start date and july 30 2014 as end date it should not be allowed to execute more.please help thanks in advance.

    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
    {
        //

}

Upvotes: 0

Views: 240

Answers (1)

Wain
Wain

Reputation: 119031

Add NSYearCalendarUnit to unitFlags, then when you have obtained the components you can request the year. This will deal with leap years better than you trying to count months and days or calculate the end date (unless you use the components to add a single year to the date to get the end date).

Upvotes: 1

Related Questions