以下是来自 Cocoa 的方法,可帮助您获取相关信息(不确定它们是否都在 coca-touch 中可用)。
NSDate * today = [NSDate date];
NSLog(@"today: %@", today);
NSString * str = @"Thu, 21 May 09 19:10:09 -0700";
NSDate * past = [NSDate dateWithNaturalLanguageString:str
locale:[[NSUserDefaults
standardUserDefaults] dictionaryRepresentation]];
NSLog(@"str: %@", str);
NSLog(@"past: %@", past);
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit |
NSSecondCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:past
toDate:today
options:0];
NSLog(@"months: %d", [components month]);
NSLog(@"days: %d", [components day]);
NSLog(@"hours: %d", [components hour]);
NSLog(@"seconds: %d", [components second]);
NSDateComponents 对象似乎包含相关单位的差异(如指定的那样)。
如果您指定所有单位,则可以使用此方法:
void dump(NSDateComponents * t)
{
if ([t year]) NSLog(@"%d years ago", [t year]);
else if ([t month]) NSLog(@"%d months ago", [t month]);
else if ([t day]) NSLog(@"%d days ago", [t day]);
else if ([t minute]) NSLog(@"%d minutes ago", [t minute]);
else if ([t second]) NSLog(@"%d seconds ago", [t second]);
}
如果你想自己计算,你可以看看:
NSDate timeIntervalSinceDate
然后在算法中使用秒。
免责声明:如果此接口被弃用(我尚未检查),Apple 通过NSDateFormatters 执行此操作的首选方式(如下面的 cmets 建议)看起来也很简洁 - 我出于历史原因,我会保留我的答案,对于某些人来说看看使用的逻辑可能仍然有用。