Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 383
akv Avatar asked Jan 09 '10 18:01

akv


2 Answers

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];
like image 125
Chuck Avatar answered Sep 30 '22 17:09

Chuck


Check out this project: https://github.com/kevinlawler/NSDate-TimeAgo

It is a category for NSDate which does this.

like image 28
ddiego Avatar answered Sep 30 '22 17:09

ddiego