0

I'm creating a Twitter Client and I call this from the twitter API to get the timestamp for a tweet.

NSString *dateString = [twitterDictionary valueForKey:@"created_at"];
cell.dateSinceTweetLabel.text = dateString;

Which gives me a date, but in all other twitter clients I use, they show a countdown of seconds since the tweet, then to minutes since the tweet.

Are they creating some sort of timer? I'm just very interested in how this is done because I think it's a key feature to have in my app.

Thanks a bunch in advance!

Justin Cabral
  • 565
  • 1
  • 6
  • 20

2 Answers2

0

I'd imagine what they are doing is something similar to

NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *tweetCreatedDate = [dateFormatter dateFromString:dateString];
NSTimeInterval dateDifferenceInSeconds = [now timeIntervalSinceDate:tweetCreatedDate];
cell.dateSinceTweetLabel.text = [NSString stringWithFormat:@"%f seconds ago", dateDifferenceInSeconds];
aahrens
  • 5,522
  • 7
  • 39
  • 63
0

In my opinion the difficult part of this question is getting the date in a format other than:

Tue May 20 03:09:05 +0000 2014

There are a number of different answers on this topic all slightly different and most of them seem to be wrong (as in didn't work for me)This link has loads of answers, all slightly different, with only one working for me)

First get the date and change its format to one you want:

NSString * createdDate = dict[@"created_at"];

NSDateFormatter * df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEE MMM d HH:mm:ss Z y"];
NSDate * newDate = [df dateFromString:createdDate];

This will now get the date in the format: 2014-05-20 03:09:05 +0000 which can be used for comparison

NSTimeInterval secondsElapsed = [[NSDate date] timeIntervalSinceDate:newDate];

Now we have the seconds different between the two times we can easily calculate the hours, minutes etc:

daysDifferent = secondsElapsed/60*60*24
hoursDifferent = secondsElapsed/60*60
minutesDifferent = secondsElapsed/60
secondsDifferent = secondsElapsed/60*60*24

You could also calculate the hours, minutes and seconds using modulo (%) but that's easy enough to do on your own (or you can look here)

Community
  • 1
  • 1
sam_smith
  • 6,023
  • 3
  • 43
  • 60