据时间戳计算距离当前时间多久(NSDate分类)

根据时间戳计算距离当前时间多久

此处是给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];

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • pragma mark NSDate:获取时间的一个类 //// 获取当前时间:获取到的date对象是零时区的时...
    向日葵_wwx阅读 6,225评论 3 4
  • iOS开发中,经常会遇到各种各样的时间问题,8小时时差,时间戳,求时间间隔,农历等等。解决办法网上比比皆是,但大多...
    小李龍彪阅读 6,441评论 1 6
  • 说在前面 公司项目出了问题之后,上网差了很多资料,最后就有一个还是比较靠谱,剩下的都是说8小时,太肤浅,今天将这些...
    mkb2阅读 14,742评论 26 86
  • 那年还在中石油。每到夏天,最爱的就是约上大石吹风聊天儿,撸串儿喝酒…聊过往青春,逗比侃大山。高兴了就笑,开心了就闹...
    夏沫er阅读 517评论 0 1
  • 初入职场的独孤(猪脚),以一口好声音的光环进入了客服堂,每天与门客进行唇枪舌战,那家伙,血淋淋的口水战,让电话的收...
    3b5839a1ae08阅读 235评论 1 0