How to use NSTimeInterval?

I am new to Xcode and I have the following problem:

I need a method that gives me the time that has passed since this or that date so far. If it was 2 years ago, I want to return the string "2 years ago", but if it was 5 minutes ago, I want her to return the string with "5 minutes ago".

I already checked NSTimeInterval and NSDateFormatter, but I could not find a way to make it work.

+7
source share
2 answers

Just to get you started ...

You will create a key date as follows:

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]; 

The current date can be obtained as follows:

 NSDate *now = [NSDate date]; 

The time interval is in seconds, so ...

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

I am sure you can understand it here ...

This answer may help you.

+14
source

Thanks, I was wondering if there is an easier way to do this without so many lines of code.

You can create a key date as follows:

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

or you try this: https://github.com/billgarrison/SORelativeDateTransformer

+2
source

All Articles