#define dateFormatDefine @"yyyy-MM-dd HH:mm:ss"
+ (NSString *)date:(NSDate*)date date2:(NSDate *)date2 {
NSDateFormatter *fmt = [[NSDateFormatteralloc]init];
// 如果是真机调试,转换这种欧美时间,需要设置locale
fmt.locale = [[NSLocalealloc]initWithLocaleIdentifier:@"UTC"];
fmt.dateFormat =dateFormatDefine;
// 当前时间
// NSDate *now = [NSDate date];
//日历对象(方便比较两个日期之间的差距)
NSCalendar *calendar = [NSCalendarcurrentCalendar];
// NSCalendarUnit 枚举代表想获得哪些差值
NSCalendarUnit unit = NSCalendarUnitYear |NSCalendarUnitWeekOfMonth |NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute |NSCalendarUnitSecond;
//计算两个日期之间的差值
NSDateComponents *cmps = [calendarcomponents:unitfromDate:datetoDate:date2options:0];
//第一个时间的年月日时分秒
NSDateComponents *createDateCmps = [calendarcomponents:unitfromDate:date];
//第二个时间的年月日时分秒
NSDateComponents *nowCmps = [calendarcomponents:unitfromDate:date2];
// 日期的比较
if (createDateCmps.year == nowCmps.year) { // 今年
if (cmps.day ==1) {//昨天
fmt.dateFormat =@"昨天 HH:mm";
return [fmtstringFromDate:date2];
} elseif (cmps.day ==0){//今天
if (cmps.hour >1) { //大于1小时前
return [NSStringstringWithFormat:@"%ld小时前", cmps.hour];
} elseif (cmps.minute >=1) {
return [NSStringstringWithFormat:@"%ld分钟前", cmps.minute];
} else {
return [NSStringstringWithFormat:@"%ld秒钟前", cmps.second] ;
}
} else { //今年的其他日子不带年份的日期
fmt.dateFormat =@"MM-dd HH:mm";// dateFormatDefine //@"MM-dd HH:mm"
return [fmtstringFromDate:date];
}
} else { //非今年带年份的具体日期
fmt.dateFormat =dateFormatDefine;
return [fmtstringFromDate:date];
}
}