Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

Boon Kiat Seah
Boon Kiat Seah
66,640 Points

Having trouble with Adapting Data for Display Extra Credit Exercise

Here is my code, please tell me what is the best way to attempt this extra credit exercise. I edit the the method in the BlogPost class to return NSString that will show the age of the blogPost. However, i couldn't get it correctly. Here is what i have done so far. Thanks

- (NSString *) formattedDate {
  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

  [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

  NSDate *tempDate = [dateFormatter dateFromString:self.date];

  NSDate* now = [NSDate date];

  NSDateComponents* ageComponents = [[NSCalendar currentCalendar]
                                     components:NSYearCalendarUnit
                                     fromDate:tempDate
                                     toDate:now
                                     options:0];

  return [NSString stringWithFormat:@"%ld",(long)[ageComponents month]];
}

1 Answer

Amit Bijlani
STAFF
Amit Bijlani
Treehouse Guest Teacher

The class NSDate has a method called timeIntervalSinceNow which compares the current date and the date in the object. The number returned to you is represented in the number of seconds. So if the blog post was written yesterday then it might return 86,400 seconds or 24 hours represented as number of seconds or 24 * 60 * 60.

The basic math is that if 1 day = 86,400 seconds then you can simply divide that number to get the number of days 86,400/86,400 = 1 day. If the resulting number is more than 7 then you can return a string saying "a week ago" or if the number is more than 30 then you can return a string saying "a month ago".

To see a more complete version of this implementation check out this GitHub project: https://github.com/kevinlawler/NSDate-TimeAgo You can even use it in your own project.