次の経過時間をユーザーに表示したいと思います。
例えば、
Scanned 13 seconds ago
Scanned 2 minutes ago
Scanned 1 hour ago
Scanned 2 days ago
Scanned 1 month ago
Scanned 1 year ago
これを実現するために次の方法を使用しますが、期待どおりに機能していません。たとえば、何かをスキャンしたばかりの場合、次のように出力されます: Scanned 9 seconds 16 hours ago、これは明らかに正しくありません。それはちょうどあるべきです: 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];
}