类似这样的代码片段总是记得不是很清楚,所以今天给整理下,以后自己也可以自己也可以直接拿来使用。其实要是自己直接给写出来,还是要废一点脑细胞的。
- (NSString *)convertTime:(long long )time{
// 今天 11:20 或 刚刚 几分钟前 几小时前
// 昨天 23:23
// 2016-05-12 11:11
// 1. 创建一个日历对象
NSCalendar *calendar = [NSCalendar currentCalendar];
// 2. 获取当前时间
NSDate *currentDate = [NSDate date];
// 3. 获取当前时间的年月日
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute fromDate:currentDate];
NSInteger currentYear = components.year;
NSInteger currentMonth = components.month;
NSInteger currentDay = components.day;
NSInteger currentHour = components.hour;
NSInteger currentMinute = components.minute;
// 4. 获取发送时间
NSDate *sendDate = [NSDate dateWithTimeIntervalSince1970:time/1000];
// 5. 获取发送时间的年月日
NSDateComponents *sendComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute fromDate:sendDate];
NSInteger sendYear = sendComponents.year;
NSInteger sendMonth = sendComponents.month;
NSInteger sendDay = sendComponents.day;
NSInteger sendHour = sendComponents.hour;
NSInteger sendMin = sendComponents.minute;
NSDateFormatter *fmt = [[NSDateFormatter alloc]init];
// 6. 当前时间与发送时间的比较
if (currentYear == sendYear &&
currentMonth == sendMonth &&
currentDay == sendDay) {// 今天
if (currentHour == sendHour && currentMinute == sendMin) {//时分相同
fmt.dateFormat = @"刚刚";
}else if(currentHour == sendHour && currentMinute != sendMin){//时同分不同
NSInteger minuteInterval = currentMinute - sendMin;
NSString *fmtString = [NSString stringWithFormat:@"%ld分钟前",minuteInterval];
fmt.dateFormat = fmtString;
}else if (currentHour != sendHour){//相差多少小时
NSInteger hourInterval = currentHour - sendHour;
NSString *fmtString = [NSString stringWithFormat:@"%ld小时前",hourInterval];
fmt.dateFormat = fmtString;
}
//如果想用今天 11:20 这种形式,只要将刚刚,几分钟前,几个小时前这几行代码给注释,开启这行代码就可以了。
//fmt.dateFormat = @"今天 HH:mm";
}else if(currentYear == sendYear &&
currentMonth == sendMonth &&
currentDay == sendDay + 1){
fmt.dateFormat = @"昨天 HH:mm";
}else{
fmt.dateFormat = @"yyyy-MM-dd HH:mm";
}
return [fmt stringFromDate:sendDate];
}
再看一下如何模拟测试一下这个代码片段逻辑是否正确,调用形式如下:
//获取系统当前时间的时间戳
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval a = [date timeIntervalSince1970]*1000;
//60 * 60 * 2 表示两个小时,1000只是一个系数
NSString *timeStr2 = [self convertTime:a - 1000 * 60 * 60 * 2 ];
NSLog(@"%@",timeStr2);
顺便提下如何把时间戳转为当前时间:
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:a/1000 + 8 **60 * 60];