在iOS中添加(多长时间)detailTextLabel的时间

时间:2015-08-20 16:40:44

标签: ios objective-c text uilabel nsdate

我有一个表视图,在索引路径的行的单元格中有

cell.textLabel.text = username;
cell.detailTextLabel.text = // here i would like to display time 

在detailtextLabel中我希望显示时间:5分钟前所以它显示了消息传来的时间。

怎么可能这样做?

2 个答案:

答案 0 :(得分:1)

如果您不想自己动手,可以使用这个很棒的图书馆:https://github.com/mattt/FormatterKit

寻找TTTTimeIntervalFormatter。

NSDate *aDate = ... ;
TTTTimeIntervalFormatter *timeIntervalFormatter = [[TTTTimeIntervalFormatter alloc] init];
NSTimeInterval timeInterval = [aDate timeIntervalSinceNow];
cell.detailTextLabel.text = [self.timeIntervalFormatter stringForTimeInterval:timeInterval];

答案 1 :(得分:0)

服务器或后端必须向您发送时间戳。主要是Unix时间戳。

您可以从中创建一个NSDate对象,然后将其转换为用户友好格式并显示为NSString。

看起来像

NSDate *date = [NSDate dateWithTimeIntervalSince1970:unixTimeStamp];
NSDate *dateFromatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *formatString = [dateFormatter stringFromDate:date];
cell.detailTextLabel.text = formatString;