R.Aarthika Rajendran R.Aarthika Rajendran - 1 month ago 12
Objective-C Question

Date comparison in showing null

I am having two dates like this,

NSString *givendate = @"2016-10-07T13:01:20";
NSDate *currentDateTime = [NSDate date];


I want to calculate no of days like 5days or 6 days by comparing current date with given date.

I tried the following code.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFromString = [dateFormatter dateFromString:givendate];
NSTimeInterval diff = [currentDateTime timeIntervalSinceDate:dateFromString];
NSString *intervalString = [NSString stringWithFormat:@"%f", diff];
cell.days.text=intervalString;


But it prints "nan". any help will be appreciated.

Answer

You have to specify dateFormat for NSDateFormatter according to your date string like below, otherwise it will return nil or nan:

    NSDate *dateFromString;

    NSString *givendate = @"2016-10-07T13:01:20";
    NSDate *currentDateTime = [NSDate date];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];//Set format here accordingly
    dateFromString = [dateFormatter dateFromString:givendate];
    NSTimeInterval diff = [currentDateTime timeIntervalSinceDate:dateFromString];
    NSString *intervalString = [NSString stringWithFormat:@"%f", diff];

Above code is working for me.

Edit:

int num_days = diff / (60 * 60 * 24);
int num_seconds -= num_days * (60 * 60 * 24);
int num_hours = num_seconds / (60 * 60);
int num_seconds -= num_hours * (60 * 60);
int num_minutes = num_seconds / 60;

OR

Use NSGregorianCalendar like below:

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

    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate:dateFromString
                                              toDate:currentDateTime options:0];
    NSInteger years = [components year];
    NSInteger months = [components month];
    NSInteger days = [components day]; 
    NSLog(@"years = %ld months = %ld days = %ld",years,months,days);
Comments