Drowned
Drowned

Reputation: 443

Is there a popular method of displaying time since a unix timestamp?

I've done this hundreds of times with PHP, but now I'm learning xcode and I can't figure it out. I'm trying to display a Unix Timestamp on a tableView cell like this -> "10 minutes 24 seconds ago", "4 hours, 2 minutes ago" or "2 days 4 hours ago". Any ideas?

Upvotes: 1

Views: 720

Answers (4)

Zauce
Zauce

Reputation: 133

I ran into the same thing, heres what I came up with for unix timestamps:

-(NSString *)timeSinceNow:(float)timestamp{
NSMutableString *time = [[NSMutableString alloc]init];
NSTimeInterval ti = [[NSDate date] timeIntervalSince1970];
float diff = ti - timestamp;
//days
if (diff<60*60*24*365) {
    [time appendString:[NSString stringWithFormat:@"%d day", (int)floor(diff/(60*60*24))]];
}
//hours
if (diff<60*60*24) {
    [time appendString:[NSString stringWithFormat:@"%d hour", (int)floor(diff/(60*60))]];
}
//minutes
if (diff<60*60) {
    [time appendString:[NSString stringWithFormat:@"%d minute", (int)floor(diff/(60))]];
}
//seconds
if (diff<60) {
    [time appendString:[NSString stringWithFormat:@"%d second", (int)floor(diff)]];
}
//years
if (diff>=60*60*24*365) {
    [time appendString:[NSString stringWithFormat:@"%d year", (int)floor(diff/(60*60*24*365))]];
}
//check if its not singular (plural) - add 's' if so
if (![[time substringToIndex:2] isEqualToString:@"1 "]) {
    [time appendString:@"s"];
}
return time;
}

Upvotes: 3

Brian Gesiak
Brian Gesiak

Reputation: 6968

Try this third party library: https://github.com/billgarrison/SORelativeDateTransformer

You can install it via CocoaPods, or using the instructions in the README.

If you'd like to roll your own solution, you can get the number of seconds since the current time by using +[NSDate dateWithTimeIntervalSinceReferenceDate:], passing in a reference date of the current time, +[NSDate date]. By dividing the result using the appropriate units, you should be able to get the level of granularity you desire.

SORelativeDateTransformer takes that a step further, by allowing for localization with some clever use of -[NSBundle localizedStringForKey:value:table:].

Upvotes: 1

Wolfgang Wilke
Wolfgang Wilke

Reputation: 557

NSDate *now = [NSDate date];

should do build the difference to something and and then bind it to the cell

Upvotes: 0

Related Questions