利用时间戳来进行计算 ,需要给它一个时间:
NSString *countTime = [self intervalSinceNow:@"2015-10-29 17:00:00"];
计算时间:
- (NSString *)intervalSinceNow: (NSString *) theDate
{
NSDateFormatter *date=[[NSDateFormatter alloc] init];
[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *d=[date dateFromString:theDate];
NSTimeInterval late=[d timeIntervalSince1970]*1;
NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval now=[dat timeIntervalSince1970]*1;
NSString *timeString=@"";
NSTimeInterval cha=now-late;
if (cha/60<1)
{
timeString = [NSString stringWithFormat:@"%.0f", cha];
// timeString = [timeString substringToIndex:timeString.length-7];
timeString=[NSString stringWithFormat:@"%@秒前", timeString];
}
if (cha/3600<1) {
timeString = [NSString stringWithFormat:@"%.0f", cha/60];
// timeString = [timeString substringToIndex:timeString.length-7];
timeString=[NSString stringWithFormat:@"%@分钟前", timeString];
}
if (cha/3600>1&&cha/86400<1) {
timeString = [NSString stringWithFormat:@"%.0f", cha/3600];
// timeString = [timeString substringToIndex:timeString.length-7];
timeString=[NSString stringWithFormat:@"%@小时前", timeString];
}
if (cha/86400>1)
{
timeString = [NSString stringWithFormat:@"%.0f", cha/86400];
// timeString = [timeString substringToIndex:timeString.length-7];
timeString=[NSString stringWithFormat:@"%@天前", timeString];
}
// [date release];
return timeString;
}
输出时间:
NSLog(@"%@",countTime);
2015-10-29 17:39:35.983 fortesw[6449:202920] 40分钟前