Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Extra Credit Adapting Data for Display

This extra credit asks for displaying the age of the post. I am able to show the age of the post in months ago, weeks ago, days ago, hrs ago. It seemed a little verbose. Just wanted to ask if there was simpler way of doing the same. I create a method in the BlogPost class that returns a string of the age, and then call that in the controller. '''objective-c -(NSString*) ageOfThePost { //difference bettween today's date and blogPost date

//change blog post date to date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *blogDate = [dateFormatter dateFromString:self.date];
//For difference
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *today=[NSDate date];
unsigned int unitFlags = NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit;
NSDateComponents *dateComp = [gregorianCalendar components:unitFlags fromDate:blogDate toDate:today options:0 ];
NSString *ageUnits=nil;
NSInteger age;

//Age
if([dateComp month]>0){
    age = [dateComp month];
    ageUnits=@"months ago";
} else if ([dateComp week]>0){
    age = [dateComp week];
    ageUnits=@"weeks ago";
    NSLog(@"I am in week");
} else if ([dateComp day]>0){
    age = [dateComp day];
    ageUnits = @"days ago";
} else if ([dateComp hour]>0){
    age=[dateComp hour];
    ageUnits =@"hrs ago";
}else {
    return @"now";
}

return[NSString stringWithFormat:@"%ld %@", (long)age,ageUnits];

} '''

1 Answer

Doesn't do exactly the same thing, but you should check out the doesRelativeDateFormatting property.