Created
June 3, 2014 12:09
-
-
Save damirstuhec/65c4edb1eab6f0dd0bd0 to your computer and use it in GitHub Desktop.
NSDate category method for generating "time ago" string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSString *)timeAgo | |
{ | |
NSDate *now = [NSDate date]; | |
double deltaSeconds = fabs([self timeIntervalSinceDate:now]); | |
double deltaMinutes = deltaSeconds / 60.0f; | |
int minutes; | |
if(deltaSeconds < 5) | |
{ | |
return NSDateTimeAgoLocalizedStrings(@"Just now"); | |
} | |
else if(deltaSeconds < 60) | |
{ | |
return [self stringFromFormat:@"%%d %@seconds ago" withValue:deltaSeconds]; | |
} | |
else if(deltaSeconds < 120) | |
{ | |
return NSDateTimeAgoLocalizedStrings(@"1 minute ago"); | |
} | |
else if (deltaMinutes < 60) | |
{ | |
return [self stringFromFormat:@"%%d %@minutes ago" withValue:deltaMinutes]; | |
} | |
else if (deltaMinutes < 120) | |
{ | |
return NSDateTimeAgoLocalizedStrings(@"An hour ago"); | |
} | |
else if (deltaMinutes < (24 * 60)) | |
{ | |
minutes = (int)floor(deltaMinutes/60); | |
return [self stringFromFormat:@"%%d %@hours ago" withValue:minutes]; | |
} | |
else if (deltaMinutes < (24 * 60 * 2)) | |
{ | |
return NSDateTimeAgoLocalizedStrings(@"Yesterday"); | |
} | |
else if (deltaMinutes < (24 * 60 * 7)) | |
{ | |
minutes = (int)floor(deltaMinutes/(60 * 24)); | |
return [self stringFromFormat:@"%%d %@days ago" withValue:minutes]; | |
} | |
else if (deltaMinutes < (24 * 60 * 14)) | |
{ | |
return NSDateTimeAgoLocalizedStrings(@"Last week"); | |
} | |
else if (deltaMinutes < (24 * 60 * 31)) | |
{ | |
minutes = (int)floor(deltaMinutes/(60 * 24 * 7)); | |
return [self stringFromFormat:@"%%d %@weeks ago" withValue:minutes]; | |
} | |
else if (deltaMinutes < (24 * 60 * 61)) | |
{ | |
return NSDateTimeAgoLocalizedStrings(@"Last month"); | |
} | |
else if (deltaMinutes < (24 * 60 * 365.25)) | |
{ | |
minutes = (int)floor(deltaMinutes/(60 * 24 * 30)); | |
return [self stringFromFormat:@"%%d %@months ago" withValue:minutes]; | |
} | |
else if (deltaMinutes < (24 * 60 * 731)) | |
{ | |
return NSDateTimeAgoLocalizedStrings(@"Last year"); | |
} | |
minutes = (int)floor(deltaMinutes/(60 * 24 * 365)); | |
return [self stringFromFormat:@"%%d %@years ago" withValue:minutes]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment