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);