0

我正在创建一个 Twitter 客户端,并从 twitter API 调用它来获取推文的时间戳。

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

这给了我一个日期,但是在我使用的所有其他 Twitter 客户端中,它们显示自推文以来的秒数,然后是自推文以来的分钟数。

他们是在创造某种计时器吗?我只是对如何做到这一点非常感兴趣,因为我认为这是我的应用程序中的一个关键功能。

提前致谢!

4

2 回答 2

0

在我看来,这个问题的困难部分是以以下格式获取日期:

2014 年 5 月 20 日星期二 03:09:05 +0000

关于这个主题有许多不同的答案都略有不同,其中大多数似乎是错误的(因为对我不起作用)这个链接有很多答案,都略有不同,只有一个对我有用

首先获取日期并将其格式更改为您想要的格式:

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

现在将获取格式为:2014-05-20 03:09:05 +0000 的日期,可用于比较

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

现在我们有了两次不同的秒数,我们可以轻松计算小时、分钟等:

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

您还可以使用模 (%) 计算小时、分钟和秒,但这很容易自己完成(或者您可以查看此处

于 2014-05-21T01:45:35.243 回答
0

我想他们正在做的事情类似于

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];
于 2013-09-26T17:55:16.813 回答