根據(jù)時間戳計算距離當(dāng)前時間多久
此處是給NSDate添加一個分類方法
1. 根據(jù)時間戳獲取NSDate對象
注意:此處我的時間戳是精確到毫秒的腰埂,實際計算的時候要求精確到秒就行了情萤,所以此處乘以0.001
+(NSDate*)getDateFromTimeInterval:(NSTimeInterval)interval{
if (interval == 0) {
return [NSDate date];
}
return [NSDate dateWithTimeIntervalSince1970:interval * 0.001 ];
}
2. timeAgo用于獲取NSDate對象相對于當(dāng)前時間的距離
- (NSString *)timeAgo
{
// 獲取當(dāng)前時間
NSDate *now = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
// Returns the interval between the receiver and another given date.
// 獲取過去的時間戳,給定日期,過去的時間——現(xiàn)在時間技肩,所經(jīng)歷的秒數(shù)
NSInteger interval = [zone secondsFromGMTForDate: now];
NSDate *localeDate = [now dateByAddingTimeInterval: interval];
double deltaSeconds = fabs([self timeIntervalSinceDate:localeDate]);
// 過去的時間——現(xiàn)在時間撇吞,所經(jīng)歷的分鐘
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];
}