NSString *distanceTime = [self returnFromTheTimeOfToday:@"2016-09-29 01:45:10"];
#pragma mark 默认一分钟有60秒,一小时就60分钟 一天有24小时,一周有7天,一个月有30天,一年有12个月 不考虑其他的如平年2月28天,闰月29天这些情况
- (NSString *)returnFromTheTimeOfToday:(NSString *)timeStr
{
//timeStr 字符串格式->2016-09-29 01:45:10
NSDateFormatter *form = [[NSDateFormatter alloc] init];
//设置时区
form.locale = [NSLocale localeWithLocaleIdentifier:@"cn"];
form.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *date = [form dateFromString:timeStr];
//得到当前的时间差
NSTimeInterval timeInterval = [date timeIntervalSinceNow];
timeInterval = -timeInterval;
//然后进行时间的比较
if(timeInterval < 60)
{
return [NSString stringWithFormat:@"刚刚"];
}
//分钟
NSInteger minute = timeInterval / 60;
if(minute < 60)
{
return [NSString stringWithFormat:@"%ld分钟之前",minute];
}
NSInteger hours = minute / 60;
if(hours < 24)
{
return [NSString stringWithFormat:@"%ld小时之前",hours];
}
NSInteger day = hours / 24;
NSInteger month = day/30;
NSInteger year = month/12;
if(day <= 1)
{
form.dateFormat = @"HH:mm";
NSString *oldtime = [form stringFromDate:date];
return [NSString stringWithFormat:@"昨天 %@",oldtime];
}
if(day < 7)
{
return [NSString stringWithFormat:@"%ld天之前",day];
}
if((day/7)<4)
{
return [NSString stringWithFormat:@"%ld周之前",day/7];
}
else if(month < 12)
{
return [NSString stringWithFormat:@"%ld月之前",month];
}
else
{
form.dateFormat = @"yyyy-MM-dd HH:mm";
return [NSString stringWithFormat:@"%ld年之前",year];
}
return nil;
}
文章标题:IOS距离现在的几分,几个小时,几分钟,几天,几周几月,几年
文章起源:
http://njwzjz.com/article/jesspd.html