Skip to content

Instantly share code, notes, and snippets.

@keeguon
Created August 20, 2010 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keeguon/540019 to your computer and use it in GitHub Desktop.
Save keeguon/540019 to your computer and use it in GitHub Desktop.
- (NSString *)niceTimeFormat:(NSTimeInterval)interval {
// set a past flag if the timeInterval is negative and inverse it
BOOL past = NO;
if (interval < 0) {
past = YES;
interval = -interval;
}
// set some time units
double second = 1, minute, hour, day, week;
minute = second * 60;
hour = minute * 60;
day = hour * 24;
week = day * 7;
// generate a string from there
if (interval < second * 7)
return @"right now";
if (interval < minute)
return past ? [NSString stringWithFormat:@"%.0f seconds ago", floor(interval/second)] : [NSString stringWithFormat:@"In %.0f seconds", floor(interval/second)];
if (interval < minute * 2)
return past ? @"About a minute ago" : @"In about a minute";
if (interval < hour)
return past ? [NSString stringWithFormat:@"%.0f minutes ago", floor(interval/minute)] : [NSString stringWithFormat:@"In %.0f minutes", floor(interval/minute)];
if (interval < hour * 2)
return past ? @"About an hour ago" : @"In about an hour";
if (interval < day)
return past ? [NSString stringWithFormat:@"%.0f hours ago", floor(interval/hour)] : [NSString stringWithFormat:@"In %.0f hours", floor(interval/hour)];
if (interval >= day && interval < day * 2)
return past ? @"Yesterday" : @"Tomorrow";
if (interval < day * 365)
return past ? [NSString stringWithFormat:@"%.0f days ago", floor(interval/day)] : [NSString stringWithFormat:@"In %.0f days", floor(interval/day)];
else
return past ? @"Over a year ago" : @"In a year or more";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment