How to get time from a string from an NSDate object?

Basically, I get the date time string from the API, and I want to show in the application that this action happened "5 hours ago" or "3 days ago", etc ....

I am currently trying to get the NSTimeInterval method from [NSDate timeIntervalSinceNow]. And then convert the time interval again to NSDate with [NSDate dateWithTimeIntervalSince1970:interval]. Then check the interval to see if it is at least 60/3600/86400 /, etc., to set the correct format for the output NSDateFormatter object.

Is this right to do? Or is there an easier / better way to do this?

+5
source share
2 answers

NSCalendar. .

NSUInteger desiredComponents = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSDayCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *elapsedTimeUnits = [[NSCalendar currentCalendar] components:desiredComponents 
                                                                   fromDate:activityDate 
                                                                   toDate:[NSDate date] 
                                                                   options:0];
+7

All Articles