我做了這個方法,把unix時間戳變成了一個很好的可讀的相對字符串。在新的一年的前幾天可能無法正常工作,但希望你應該過於注意。
-(NSString *)relativeTime:(int)datetimestamp
{
NSDate *aDate = [NSDate dateWithTimeIntervalSince1970:datetimestamp];
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned int unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayOrdinalCalendarUnit|NSWeekdayCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit;
NSDateComponents *messageDateComponents = [calendar components:unitFlags fromDate:aDate];
NSDateComponents *todayDateComponents = [calendar components:unitFlags fromDate:[NSDate date]];
NSUInteger dayOfYearForMessage = [calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:aDate];
NSUInteger dayOfYearForToday = [calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]];
NSString *dateString;
if ([messageDateComponents year] == [todayDateComponents year] &&
[messageDateComponents month] == [todayDateComponents month] &&
[messageDateComponents day] == [todayDateComponents day])
{
dateString = [NSString stringWithFormat:@"%02d:%02d", [messageDateComponents hour], [messageDateComponents minute]];
} else if ([messageDateComponents year] == [todayDateComponents year] &&
dayOfYearForMessage == (dayOfYearForToday-1))
{
dateString = @"Yesterday";
} else if ([messageDateComponents year] == [todayDateComponents year] &&
dayOfYearForMessage > (dayOfYearForToday-6))
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
dateString = [dateFormatter stringFromDate:aDate];
[dateFormatter release];
} else {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yy"];
dateString = [NSString stringWithFormat:@"%02d/%02d/%@", [messageDateComponents day], [messageDateComponents month], [dateFormatter stringFromDate:aDate]];
[dateFormatter release];
}
return dateString;
}
這是一個很好的答案,但事實上,沒有公共的API調用(正如在mail.app中所做的那樣)是不可信的 – lol 2012-01-23 05:01:09