Get Historic Time from NSDate eg 5s ago 2m ago 3h ago
suggest changeThis can be used in various chat applications, rss feeds, and social apps where you need to have latest feeds with timestamps:
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 *dateFormater=[[NSDateFormatter alloc]init];
[dateFormater setLocale:[NSLocale currentLocale]];
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MMM d, YYYY" options:0 locale:[NSLocale currentLocale]];
[dateFormater setDateFormat:dateFormat];
str = [dateFormater stringFromDate:since];
}
return str;
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents