views:

77

answers:

1

Basically, I'm getting a date time string from an API, and I want to show in the app that this activity happened '5 hours ago' or '3 days ago', and so on...

I am currently trying to get the NSTimeInterval from [NSDate timeIntervalSinceNow] method. And then converting the time interval to NSDate again using [NSDate dateWithTimeIntervalSince1970:interval]. And then checking the interval to see if its less that 60/3600/86400/etc, to set the right format for an output NSDateFormatter object.

Is this the right way to do it? Or is there a easier/better way to do this?

+3  A: 

It's much better to use NSCalendar for this. It's designed for this sort of conversion.

NSUInteger desiredComponents = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSDayCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *elapsedTimeUnits = [[NSCalendar currentCalendar] components:desiredComponents 
                                                                   fromDate:activityDate 
                                                                   toDate:[NSDate date] 
                                                                   options:0];
Chuck
Thanks, that is much better!
akv