根据时间戳计算距离当前时间多久
此处是给NSDate添加一个分类方法
1. 根据时间戳获取NSDate对象
注意:此处我的时间戳是精确到毫秒的,实际计算的时候要求精确到秒就行了,所以此处乘以0.001
+(NSDate*)getDateFromTimeInterval:(NSTimeInterval)interval{
if (interval == 0) {
return [NSDate date];
}
return [NSDate dateWithTimeIntervalSince1970:interval * 0.001 ];
}
2. timeAgo用于获取NSDate对象相对于当前时间的距离
- (NSString *)timeAgo
{
// 获取当前时间
NSDate *now = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
// Returns the interval between the receiver and another given date.
// 获取过去的时间戳,给定日期,过去的时间——现在时间,所经历的秒数
NSInteger interval = [zone secondsFromGMTForDate: now];
NSDate *localeDate = [now dateByAddingTimeInterval: interval];
double deltaSeconds = fabs([self timeIntervalSinceDate:localeDate]);
// 过去的时间——现在时间,所经历的分钟
double deltaMinutes = deltaSeconds / 60.0f;
int minutes;
if(deltaSeconds < 5)
{
return @"刚刚";
}
else if(deltaSeconds < 60)
{
return [self stringFromFormat:@"%%d%@秒前" withValue:deltaSeconds];
}
else if(deltaSeconds < 120)
{
return @"一分钟前";
}
else if (deltaMinutes < 60)
{
return [self stringFromFormat:@"%%d%@分钟前" withValue:deltaMinutes];
}
else if (deltaMinutes < 120)
{
return @"一小时前";
}
else if (deltaMinutes < (24 * 60))
{
minutes = (int)floor(deltaMinutes/60);
return [self stringFromFormat:@"%%d%@小时前" withValue:minutes];
}
else if (deltaMinutes < (24 * 60 * 2))
{
return @"昨天";
}
else if (deltaMinutes < (24 * 60 * 7))
{
minutes = (int)floor(deltaMinutes/(60 * 24));
return [self stringFromFormat:@"%%d%@天前" withValue:minutes];
}
else if (deltaMinutes < (24 * 60 * 14))
{
return @"上周";
}
else if (deltaMinutes < (24 * 60 * 31))
{
minutes = (int)floor(deltaMinutes/(60 * 24 * 7));
return [self stringFromFormat:@"%%d%@周前" withValue:minutes];
}
else if (deltaMinutes < (24 * 60 * 61))
{
return @"上个月";
}
else if (deltaMinutes < (24 * 60 * 365.25))
{
minutes = (int)floor(deltaMinutes/(60 * 24 * 30));
return [self stringFromFormat:@"%%d%@月前" withValue:minutes];
}
else if (deltaMinutes < (24 * 60 * 731))
{
return @"去年";
}
minutes = (int)floor(deltaMinutes/(60 * 24 * 365));
return [self stringFromFormat:@"%%d%@年前" withValue:minutes];
}