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
Chris Holloway
2,427 PointsFormatting dates retrieved from an API (ugh!) Can anyone do a Rick Flair on my NSDateFormatter?
I am pulling down a date-time string from an API, and preparing it for display on a subclass of UITableViewController.
I need to display "XX minutes ago", referring to a weather observation that has taken place in the past, usually not more than 60 minutes ago.
I am having trouble, like all other newbies, figuring out how to format the various NSDate objects. My code is below. To explain...
I've created a weatherDictionary object using [NSJSONSerialization JSONObjectWithData].
Line 1 is where I pull out the observationTime string from the weatherDictionary.
From the APO, the observationTime string is formatted as such:
"Tue, 08 Jul 2014 16:30:13 -0400",
Note the format of the hours:minutes:seconds
Line 2 is where I separate out the key component of that text string by splitting the string into an NSArray.
Line 3,4 is the dateFormatter. Line 5,6 is now, and the time of observation. The objectAtIndex:4 is the hours:minutes:seconds object of the array.
The line that I'm sure is causing the trouble is where I format the string *timeAgo.
NSString *observationTime = [[weatherDictionary valueForKey:@"current_observation"] valueForKey:@"observation_time_rfc822"];
NSArray *observationTimeArray = [observationTime componentsSeparatedByString:@" "];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSDate *dateNow = [NSDate date];
NSDate *observationDate = [dateFormatter dateFromString:[observationTimeArray objectAtIndex:4]];
NSString *timeAgo = [NSString stringWithFormat:@"%f minutes ago", [dateNow timeIntervalSinceDate:observationDate]];
self.timeSinceObservation = timeAgo;
When I log this to the console I get:
458081411.768475 minutes ago
NSDate Woooooooo!!
1 Answer
Patrick Cooney
12,216 PointsSo I'm not positive on this but, if my understanding of NSDate is correct, it looks like you're comparing an hour:min:sec string to the [NSDate date] return value which returns a full date including day, month, etc. Try splitting up the return value of [NSDate date] (like you did with the API return) so that you're comparing apples to apples. no pun intended.