//dateString 格式:2015-12-17 08:08:08
/*
传入时间与现在时间差距60秒内,输出@“刚刚”
差距1小时内,输出@“xx分钟前”
差距1-24小时内,输出@“xx小时前”
差距大于一天,输出@“xx天前”
差距大于30天,输出@“xx个月前”
差距大于365天,输出@“完整日期”
*/
main.m ===========================================================#import <Foundation/Foundation.h>
#import "Tool.h"
int main(int argc,const char * argv[]) {
@autoreleasepool {
/*
char *Cstring = "This is a String!"; //C语言字符串
NSString *astring = [[NSString alloc] initWithCString:Cstring]; //转换到OC字符串
*/
// NSString *dateString;//距离时间
NSString *dateString=@"2015-12-17 8:08:08";
/*
//控制台输入方式
NSMutableArray *array=[NSMutableArray array];
char shuru[1000];
printf("输入时间(yyyy-MM-dd HH:mm:ss):\n");
gets(shuru);
NSString *dateString = [[NSString alloc] initWithCString:shuru];
*/
NSLog(@"%@",[ToolhandleDate:dateString]);
}
return 0;
}
=================================================================
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
{
NSString *string;
NSDateFormatter *dateFormatter=[NSDateFormatternew];
[dateFormatter setTimeZone:[NSTimeZonetimeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date=[dateFormatter dateFromString:dateString];
NSTimeInterval timeInterval=date.timeIntervalSinceNow;
timeInterval=-(timeInterval-28800);
/*
传入时间与现在时间差距60秒内,输出@“刚刚”
差距1小时内,输出@“xx分钟前”
差距1-24小时内,输出@“xx小时前”
差距大于一天,输出@“xx天前”
差距大于30天,输出@“xx个月前”
差距 大于365天,输出@“完整日期”
*/
if (timeInterval<60)
{
string=@"刚刚";
}
if (timeInterval>60 && timeInterval<3600)//大于1分小于1个小时
{
float mm;
mm=(timeInterval/60);
string=[NSString stringWithFormat:@"%.0f分钟以前",mm];
}
if (timeInterval>3600 && timeInterval<86400)
{
float HH;
HH=((timeInterval/60)/60);
string=[NSString stringWithFormat:@"%.0f小时以前",HH];
}
if(timeInterval>86400 && timeInterval<2592000)
{
float day;
day=((timeInterval/60)/60)/24;
string=[NSString stringWithFormat:@"%.0f天前",day];
}
if(timeInterval>2592000 && timeInterval<31104000)
{
float year;
year=(((timeInterval/60)/60)/24)/30;
string=[NSString stringWithFormat:@"%.0f个月前",year];
}
if(timeInterval>31104000)
{
string=[NSString stringWithFormat:@"%@",dateString];
}
//string=[NSString stringWithFormat:@"%f",timeInterval];
return string;
}
@end