Skip to content

Instantly share code, notes, and snippets.

@iAladdin
Created August 16, 2011 05:48
Show Gist options
  • Save iAladdin/1148506 to your computer and use it in GitHub Desktop.
Save iAladdin/1148506 to your computer and use it in GitHub Desktop.
NSDate category
@implementation NSDate (Extensions)
-(NSString *)timeAgo {
NSDate *now = [NSDate date];
double deltaMinutes = fabs([self timeIntervalSinceDate:now]) / 60.0f;
if (deltaMinutes < 60){
return @"a few minutes ago";
} else if (deltaMinutes < 120) {
return @"an hour ago";
} else if (deltaMinutes < (24 * 60)) {
return [NSString stringWithFormat:@"%d hours ago", (int)floor(deltaMinutes/60)];
} else if (deltaMinutes < (24 * 60 * 2)) {
return @"yesterday";
} else if (deltaMinutes < (24 * 60 * 7)) {
return [NSString stringWithFormat:@"%d days ago", (int)floor(deltaMinutes/(60 * 24))];
} else if (deltaMinutes < (24 * 60 * 14)) {
return @"last week";
} else if (deltaMinutes < (24 * 60 * 31)) {
return [NSString stringWithFormat:@"%d weeks ago", (int)floor(deltaMinutes/(60 * 24 * 7))];
} else if (deltaMinutes < (24 * 60 * 61)) {
return @"last month";
} else if (deltaMinutes < (24 * 60 * 365.25)) {
return [NSString stringWithFormat:@"%d months ago", (int)floor(deltaMinutes/(60 * 24 * 30))];
} else if (deltaMinutes < (24 * 60 * 731)) {
return @"last year";
}
return [NSString stringWithFormat:@"%d years ago", (int)floor(deltaMinutes/(60 * 24 * 365))];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment