Given a specific DateTime
value, how do I display relative time, like:
+ (NSString *)timeAgoString:(NSDate *)date {
int delta = -(int)[date timeIntervalSinceNow];
if (delta < 60)
{
return delta == 1 ? @"one second ago" : [NSString stringWithFormat:@"%i seconds ago", delta];
}
if (delta < 120)
{
return @"a minute ago";
}
if (delta < 2700)
{
return [NSString stringWithFormat:@"%i minutes ago", delta/60];
}
if (delta < 5400)
{
return @"an hour ago";
}
if (delta < 24 * 3600)
{
return [NSString stringWithFormat:@"%i hours ago", delta/3600];
}
if (delta < 48 * 3600)
{
return @"yesterday";
}
if (delta < 30 * 24 * 3600)
{
return [NSString stringWithFormat:@"%i days ago", delta/(24*3600)];
}
if (delta < 12 * 30 * 24 * 3600)
{
int months = delta/(30*24*3600);
return months <= 1 ? @"one month ago" : [NSString stringWithFormat:@"%i months ago", months];
}
else
{
int years = delta/(12*30*24*3600);
return years <= 1 ? @"one year ago" : [NSString stringWithFormat:@"%i years ago", years];
}
}