How to use NSTimeInterval properly? [closed]

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.

2

2 Answers

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.

0

Thank you, I was wondering if there is an easier way of doing it without having so many lines of code.

You could create the reference date like this:

NSDate *referenceDate = [NSDate date]; [[NSCalendar currentCalendar] rangeOfUnit:NSYearCalendarUnit startDate:&referenceDate interval:NULL forDate:referenceDate]; 

or you try this:

You Might Also Like