IOS calculates how long the last date is now, such as xx hours ago and xx minutes ago, iosxx
/**
* Calculate the distance between the last date and the current time
*
* @ Param lastTime the last date (corresponding to the format)
* @ Param format1 last date format
* @ Param currentTime recent date (corresponding to the format)
* @ Param format2 Latest Date Format
*
* @ Return xx minutes ago, xx hours ago, xx days ago
*/
+ (
NSString
*)timeIntervalFromLastTime:(
NSString
*)lastTime
lastTimeFormat:(
NSString
*)format1
ToCurrentTime:(
NSString
*)currentTime
currentTimeFormat:(
NSString
*)format2{
// Last time
NSDateFormatter
*dateFormatter1 = [[
NSDateFormatter
alloc]init];
dateFormatter1.dateFormat = format1;
NSDate
*lastDate = [dateFormatter1 dateFromString:lastTime];
// Current time
NSDateFormatter
*dateFormatter2 = [[
NSDateFormatter
alloc]init];
dateFormatter2.dateFormat = format2;
NSDate
*currentDate = [dateFormatter2 dateFromString:currentTime];
return
[Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];
}
+ (
NSString
*)timeIntervalFromLastTime:(
NSDate
*)lastTime ToCurrentTime:(
NSDate
*)currentTime{
NSTimeZone
*timeZone = [
NSTimeZone
systemTimeZone];
// Last time
NSDate
*lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
// Current time
NSDate
*currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
// Time Interval
NSInteger
intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
// Second, minute, hour, day, month, and year
NSInteger
minutes = intevalTime / 60;
NSInteger
hours = intevalTime / 60 / 60;
NSInteger
day = intevalTime / 60 / 60 / 24;
NSInteger
month = intevalTime / 60 / 60 / 24 / 30;
NSInteger
yers = intevalTime / 60 / 60 / 24 / 365;
if
(minutes <= 10) {
return
@ "Just now"
;
}
else
if
(minutes < 60){
return
[
NSString
stringWithFormat:
@ "% Ld minutes ago"
,(
long
)minutes];
}
else
if
(hours < 24){
return
[
NSString
stringWithFormat:
@ "% Ld hours ago"
,(
long
)hours];
}
else
if
(day < 30){
return
[
NSString
stringWithFormat:
@ "% Ld days ago"
,(
long
)day];
}
else
if
(month < 12){
NSDateFormatter
* df =[[
NSDateFormatter
alloc]init];
df.dateFormat =
@ "M-d"
;
NSString
* time = [df stringFromDate:lastDate];
return
time;
}
else
if
(yers >= 1){
NSDateFormatter
* df =[[
NSDateFormatter
alloc]init];
df.dateFormat =
@ "Yyyy-M-d"
;
NSString
* time = [df stringFromDate:lastDate];
return
time;
}
return
@""
;
}
Use:NSLog
(
@"\n\nresult: %@"
, [Utilities timeIntervalFromLastTime:
@ "December 8, 2015"
lastTimeFormat:
@ "Yyyy-MM-dd HH: mm"
ToCurrentTime:
@"2015/12/08 16:12"
currentTimeFormat:
@"yyyy/MM/dd HH:mm"
]);
The output result is as follows: