5

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?

akv
  • 3,693
  • 3
  • 17
  • 11

2 Answers2

7

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
  • 234,037
  • 30
  • 302
  • 389
  • The problem with doing it this way is that something that happened, let's say, 4 days ago will be expressed as "3 days, 14 hours, 6 minutes", etc. I suggest using this answer from another question: http://stackoverflow.com/a/932130/591487 – inorganik Jul 29 '14 at 18:27
4

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

It is a category for NSDate which does this.

ddiego
  • 3,247
  • 1
  • 28
  • 18