此函数将返回从 sec 到 years 的 NSString。就像您的日期是“1 秒前”或“1 分钟前”或“1 年前”等等......它会同样返回......
-(NSString*)HourCalculation:(NSString*)PostDate
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormat setTimeZone:gmt];
NSDate *ExpDate = [dateFormat dateFromString:PostDate];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit|NSWeekCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:ExpDate toDate:[NSDate date] options:0];
NSString *time;
if(components.year!=0)
{
if(components.year==1)
{
time=[NSString stringWithFormat:@"%ld year",(long)components.year];
}
else
{
time=[NSString stringWithFormat:@"%ld years",(long)components.year];
}
}
else if(components.month!=0)
{
if(components.month==1)
{
time=[NSString stringWithFormat:@"%ld month",(long)components.month];
}
else
{
time=[NSString stringWithFormat:@"%ld months",(long)components.month];
}
}
else if(components.week!=0)
{
if(components.week==1)
{
time=[NSString stringWithFormat:@"%ld week",(long)components.week];
}
else
{
time=[NSString stringWithFormat:@"%ld weeks",(long)components.week];
}
}
else if(components.day!=0)
{
if(components.day==1)
{
time=[NSString stringWithFormat:@"%ld day",(long)components.day];
}
else
{
time=[NSString stringWithFormat:@"%ld days",(long)components.day];
}
}
else if(components.hour!=0)
{
if(components.hour==1)
{
time=[NSString stringWithFormat:@"%ld hour",(long)components.hour];
}
else
{
time=[NSString stringWithFormat:@"%ld hours",(long)components.hour];
}
}
else if(components.minute!=0)
{
if(components.minute==1)
{
time=[NSString stringWithFormat:@"%ld min",(long)components.minute];
}
else
{
time=[NSString stringWithFormat:@"%ld mins",(long)components.minute];
}
}
else if(components.second>=0)
{
if(components.second==0)
{
time=[NSString stringWithFormat:@"1 sec"];
}
else
{
time=[NSString stringWithFormat:@"%ld secs",(long)components.second];
}
}
return [NSString stringWithFormat:@"%@ ago",time];
}