.h文件
//格式化時(shí)間字符串
+ (NSString*)handleTimeType:(NSString*)date;
+ (NSString*)handleTimeTypeStr:(NSDate*)dateString;
.m文件
+ (NSString*)handleTimeTypeStr:(NSDate*)dateString{
NSDateFormatter*formatter = [[NSDateFormatteralloc]init];
formatter.dateFormat=@"yyyy-MM-dd HH:mm:ss";
NSString*dateStr = [formatterstringFromDate:dateString];
return[selfhandleTimeType:dateStr];
}
+ (NSString*)handleTimeType:(NSString*)date{
NSDateFormatter*formatter = [[NSDateFormatteralloc]init];
NSDate*currentDate = [NSDatedateWithTimeIntervalSinceNow:0];
formatter.dateFormat=@"yyyy-MM-dd HH:mm:ss";
NSDate*localDate = [formatterdateFromString:date];
if([selfisThisYear:localDate]) {
NSTimeIntervaltimeInterval =ABS([localDate timeIntervalSinceDate:currentDate]);
if(timeInterval <60) {
return@"剛剛";
}elseif(timeInterval <3600){
NSIntegerminuter = timeInterval /60;
return[NSStringstringWithFormat:@"%ld分鐘前",(long)minuter];
}elseif(timeInterval <3600*24){
formatter.dateFormat=@"yyyy-MM-dd";
NSString*currentDateStr = [formatterstringFromDate:currentDate];
NSString*createAtStr = [formatterstringFromDate:localDate];
if([currentDateStrisEqualToString:createAtStr]) {
//是今天
NSIntegerhours = timeInterval /3600;
return[NSStringstringWithFormat:@"%ld小時(shí)前",(long)hours];
}else{
//是昨天
formatter.dateFormat=@"昨天HH:mm";
}
}else{
formatter.dateFormat=@"MM-dd HH:mm";
}
}else{
//不是今年
formatter.dateFormat=@"yyyy-MM-dd HH:mm";
}
return[formatterstringFromDate:localDate];
}
+ (BOOL)isThisYear:(NSDate*)createAt{
NSDateFormatter*formatter = [[NSDateFormatteralloc]init];
formatter.dateFormat=@"yyyy";
//獲取年份
NSString*dateYearStr = [formatterstringFromDate:createAt];
//獲取當(dāng)前年份
NSString*currentYearStr = [formatterstringFromDate:[NSDatedate]];
return[dateYearStrisEqualToString:currentYearStr];
}
跟微博一樣哦,我覺得還不錯(cuò),分享給大家.