Skip to content

Instantly share code, notes, and snippets.

@trungtran
Last active December 10, 2015 21:48
Show Gist options
  • Save trungtran/4497556 to your computer and use it in GitHub Desktop.
Save trungtran/4497556 to your computer and use it in GitHub Desktop.
+ (NSString *)sinceStringForDate:(NSDate *)date longFormat:(BOOL)longFormat
{
NSTimeInterval sinceNow = -[date timeIntervalSinceNow];
NSString *num = @"";
NSString *units = @"";
const NSTimeInterval ONE_MIN = 60;
const NSTimeInterval ONE_HOUR = ONE_MIN * 60;
const NSTimeInterval ONE_DAY = ONE_HOUR * 24;
if (roundf(sinceNow) <= 0.0f)
{
num = @"now";
}
else if (sinceNow < ONE_MIN)
{
num = [NSString stringWithFormat:@"%2.f", floorf(sinceNow)];
units = longFormat ? @" seconds ago" : @"s";
}
else if (sinceNow < ONE_HOUR)
{
num = [NSString stringWithFormat:@"%2.f", floorf(sinceNow / ONE_MIN)];
units = longFormat ? @" minutes ago" : @"m";
}
else if (sinceNow > ONE_HOUR && sinceNow < ONE_HOUR * 2)
{
num = [NSString stringWithFormat:@"%2.f", floorf(sinceNow / ONE_HOUR)];
units = longFormat ? @" hour ago" : @"h";
}
else if (sinceNow < ONE_DAY)
{
num = [NSString stringWithFormat:@"%2.f", floorf(sinceNow / ONE_HOUR)];
units = longFormat ? @" hours ago" : @"h";
}
else
{
num = [NSString stringWithFormat:@"%2.f", floorf(sinceNow / ONE_DAY)];
units = longFormat ? @" days ago" : @"d";
}
return [NSString stringWithFormat:@"%@%@", num, units];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment