How to use NSTimeInterval properly?

Joaocdn picture Joaocdn · Nov 9, 2012 · Viewed 38.4k times · Source

I'm new to Xcode and I have the following problem:

I want a method that gives me the time that as passed since a given date till now. If it was 2 years ago I want to return a string "2 years ago", but if it was 5 minutes ago I want it to return a string with "5 minutes ago".

I've already checked NSTimeInterval and NSDateFormatter but I couldn't find a way to make it work.

Answer

Rok Jarc picture Rok Jarc · Nov 9, 2012

Just to get you started...

You would create a reference date like this:

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

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.year = 2012;
dateComponents.month = 1;
dateComponents.day = 1;
dateComponents.hour = 0;
dateComponents.minute = 0;
dateComponents.second = 0;

NSDate *referenceDate = [gregorian dateFromComponents: dateComponents];

Current date can be obtained like this:

NSDate *now = [NSDate date];

Time interval is in seconds, so...

NSTimeInterval interval = [now timeIntervalSinceDate:referenceDate];
NSLog (@"reference date was %.0f seconds ago", interval);

I'm sure you'll be able to figure it out on yourself from here on...

This answer might help you out.