Get Historic Time from NSDate eg 5s ago 2m ago 3h ago
suggest changeThis can be used in chat applications, RSS feeds, and social apps that show a timestamp on the latest items. A future date has a negative interval and is formatted as a negative number of seconds ago. The year symbol is yyyy; YYYY is the week-based year.
Objective-C
- (NSString *)getHistoricTimeText:(NSDate *)since
{
NSString *str;
NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:since];
if(interval < 60)
str = [NSString stringWithFormat:@"%is ago",(int)interval];
else if(interval < 3600)
{
int minutes = interval/60;
str = [NSString stringWithFormat:@"%im ago",minutes];
}
else if(interval < 86400)
{
int hours = interval/3600;
str = [NSString stringWithFormat:@"%ih ago",hours];
}
else
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MMM d, yyyy" options:0 locale:[NSLocale currentLocale]];
[dateFormatter setDateFormat:dateFormat];
str = [dateFormatter stringFromDate:since];
}
return str;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents