Tool .h
#import <Foundation/Foundation.h>
@interface Tool : NSObject
+(NSString *)handleDate:(NSString *)dateString;
@end
Tool.m
#import "Tool.h"
@implementation Tool
+(NSString *)handleDate:(NSString *)dateString
{
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date1 = [dateFormatter dateFromString:dateString];
NSMutableString *string = [NSMutableString new];
if (date1 == nil)
{
return @"请按格式输入正确日期!";
}
NSTimeInterval timeInvterval = date1.timeIntervalSinceNow;
timeInvterval *= -1 ;
if (timeInvterval >=0 && timeInvterval < 60)
{
[string appendString:@"刚刚"];
}
else if (timeInvterval >= 60 && timeInvterval < 3600)
{
int min = timeInvterval / 60;
[string appendFormat:@"%d分钟前",min];
}
else if (timeInvterval >= 3600 && timeInvterval < 3600*24)
{
int hour = timeInvterval / 3600;
[string appendFormat:@"%d小时前",hour];
}
else if (timeInvterval >= 3600*24 && timeInvterval < 3600*24*30)
{
int day = timeInvterval / (3600*24);
[string appendFormat:@"%d日前",day];
}
else if (timeInvterval >= 3600*24*30 && timeInvterval<3600*24*30*12)
{
int month = timeInvterval/(3600*24*30);
[string appendFormat:@"%d个月前",month];
}
else if (timeInvterval > 3600*24*30*12)
{
string = [NSMutableString stringWithString:dateString];
}
else
{
NSString *string2 = @"请按格式输入正确日期";
[string appendString:string2];
}
return string;
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Tool.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *string = @"2015-12-18 08:44:44";
NSString *string1 = [Tool handleDate:string];
NSLog(@"%@",string1);
}
return 0;
}