I'd like to display to the user the following elapsed times:
e.g,
Scanned 13 seconds ago
Scanned 2 minutes ago
Scanned 1 hour ago
Scanned 2 days ago
Scanned 1 month ago
Scanned 1 year ago
I use the following method to achieve this, however it's not working quite as I expected. For example if I've just scanned something then it outputs: Scanned 9 seconds 16 hours ago, which is obviously not correct. It should just be: Scanned 9 seconds ago.
+ (NSString *)elapsedTime:(NSDate *)date {
NSUInteger desiredComponents = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *elapsedTimeUnits = [[NSCalendar currentCalendar] components:desiredComponents
fromDate:date
toDate:[NSDate date]
options:0];
NSString *stringFormat = nil;
stringFormat = [NSString stringWithFormat:@"%@", [elapsedTimeUnits year] > 0 ? ([NSString stringWithFormat: @"%d year%@ ", [elapsedTimeUnits year], [elapsedTimeUnits year] == 1 ? @"" : @"s"]) : @""];
stringFormat = [NSString stringWithFormat:@"%@%@", stringFormat, [elapsedTimeUnits month] > 0 ? ([NSString stringWithFormat: @"%d month%@ ", [elapsedTimeUnits month], [elapsedTimeUnits month] == 1 ? @"" : @"s"]) : @""];
stringFormat = [NSString stringWithFormat:@"%@%@", stringFormat, [elapsedTimeUnits week] > 0 ? ([NSString stringWithFormat: @"%d week%@ ", [elapsedTimeUnits week], [elapsedTimeUnits week] == 1 ? @"" : @"s"]) : @""];
stringFormat = [NSString stringWithFormat:@"%@%@", stringFormat, [elapsedTimeUnits day] > 0 ? ([NSString stringWithFormat: @"%d day%@ ", [elapsedTimeUnits day], [elapsedTimeUnits day] == 1 ? @"" : @"s"]) : @""];
stringFormat = [NSString stringWithFormat:@"%@%@", stringFormat, [elapsedTimeUnits hour] > 0 ? ([NSString stringWithFormat: @"%d hour%@ ", [elapsedTimeUnits hour], [elapsedTimeUnits hour] == 1 ? @"" : @"s"]) : @""];
stringFormat = [NSString stringWithFormat:@"%@%@", stringFormat, [elapsedTimeUnits minute] > 0 ? ([NSString stringWithFormat: @"%d minute%@ ", [elapsedTimeUnits minute], [elapsedTimeUnits minute] == 1 ? @"" : @"s"]) : @""];
stringFormat = [NSString stringWithFormat:@"%@%@", stringFormat, [elapsedTimeUnits second] > 0 ? ([NSString stringWithFormat: @"%d second%@ ", [elapsedTimeUnits second], [elapsedTimeUnits second] == 1 ? @"" : @"s"]) : @""];
return [NSString stringWithFormat:@"Scanned %@ago", stringFormat];
}
You need to check each part and then append
append more by changing unit to appropriate and at the end stringFormat will contains your required string to display.
This code will display Scanned 2 years ago or Scanned 5 seconds ago