Get the difference between dates like Facebook comments on iOS

974 Views Asked by At

I want to get the difference between two dates which are being received in dot net format. I have converted the date into an NSDate. But I am not able to get the exact difference (the hours, minutes, and seconds fields are zero) between the dates. I am using the method below.

- (NSString*)calculateTimeFromDate :(NSDate*)date {

NSDate *createdDate;
NSDate *todayDate;


NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"IST"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:SS"];

NSString *str = [formatter  stringFromDate:date];
NSString *str1= [formatter stringFromDate:[NSDate date]];


createdDate = [formatter dateFromString:str];;
todayDate = [formatter dateFromString:str1];

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


NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                            fromDate:createdDate
                                              toDate:todayDate options:0];
NSInteger timeDifference = [components day];

int days = timeDifference;
NSString *timeStr;
if(days>0) {

    if(days == 1)  timeStr = [NSString stringWithFormat:@"%.0i %@",days, LString(@"DAY")];
    else           timeStr = [NSString stringWithFormat:@"%.0i %@ ",days, LString(@"DAYS")];
   } else {

    int hours = [components hour];
    if(hours >0){

        if(hours ==1)  timeStr = [NSString stringWithFormat:@"%.0i %@",hours, LString(@"HOUR")];
        else           timeStr = [NSString stringWithFormat:@"%.0i %@",hours, LString(@"HOURS")];
    } else {

        int minutes = [components minute];
        if(minutes>0) {

            if(minutes ==1 )   timeStr = [NSString stringWithFormat:@"%.0i %@",minutes, LString(@"MINUTE")];
            else               timeStr = [NSString stringWithFormat:@"%.0i %@",minutes, LString(@"MINUTES")];
        } else {

            int seconds =[components second];
            if(seconds >5)  timeStr=[NSString stringWithFormat:@"%.0i %@",seconds, LString(@"SECONDS")];
            else            timeStr = LString(@"JUST_NOW");
        }
    }
}
if(![timeStr isEqualToString:LString(@"JUST_NOW")])   timeStr = [timeStr stringByAppendingFormat:@" %@", LString(@"AGO")];
NSLog(@"%@",timeStr);
return timeStr;
}
3

There are 3 best solutions below

1
On

• Difference between two dates can be calculated by using - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

NSTimeInterval timeInterval  = [todayDate timeIntervalSinceDate:createdDate];

• Convert timeInterval into Hours, minutes and seconds.

int minutes = floor(timeInterval/60);
int seconds = trunc(timeInterval - minutes * 60);
int hours = minutes / 60;
0
On

try this: https://github.com/jonhocking/PrettyTimestamp

It's a really cool category on NSDate that returns the difference between two dates, as a nice string, like "a minute ago"

If it is not exactly what you want I'm sure it will help guide you in the right direction, or it could be modified to return the string however you like.

0
On

Don't reinvent the wheel, use a library for the task.

There are several github projects out there, but this is one of the best in my opinion, FormatterKit, create and maintained by Mattt Thomposon, the author of AFNetworking.

It works great and it provides support for localization too.