IOSで人間的な時間表示
1565 ワード
プロジェクトでは時間の表示に友好的な必要がある場合がありますが、IOS自体のNSDateはあまり爽やかではありません.Dateを処理するときは本当に頭が大きく、以下は混合Cの書き方です.
(NSString *)friendlyTime:(NSString *)datetime
{
time_t current_time = time(NULL);
static NSDateFormatter *dateFormatter =nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
dateFormatter.timeZone = [NSTimeZonetimeZoneForSecondsFromGMT:0];
}
NSDate *date = [dateFormatter dateFromString:datetime];
time_t this_time = [datetimeIntervalSince1970];
time_t delta = current_time - this_time;
if (delta <= 0) {
return @" ";
}
else if (delta <60)
return [NSStringstringWithFormat:@"%ld ", delta];
else if (delta <3600)
return [NSStringstringWithFormat:@"%ld ", delta /60];
else {
struct tm tm_now, tm_in;
localtime_r(¤t_time, &tm_now);
localtime_r(&this_time, &tm_in);
NSString *format = nil;
if (tm_now.tm_year == tm_in.tm_year) {
if (tm_now.tm_yday == tm_in.tm_yday)
format = @" %-H:%M";
else
format = @"%-m %-d %-H:%M";
}
else
format = @"%Y %-m %-d %-H:%M";
char buf[256] = {0};
strftime(buf, sizeof(buf), [format UTF8String], &tm_in);
return [NSStringstringWithUTF8String:buf];
}
}