两个NSDates之间的差异

Min*_*arg 15 iphone objective-c ios

我使用日期时间选择器来获取两个NSDates.现在我想计算这两个NSDates之间的天数.如何找到两个NSDates之间的区别.

请给我一些解决方案.

非常感谢.

mar*_*tin 56

这里有一个小宝石 - 不仅仅是几天:

// Assuming you have fistDate and secondDate

unsigned int unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitDay | NSCalendarUnitMonth;

NSDateComponents *conversionInfo = [currCalendar components:unitFlags fromDate:fistDate   toDate:secondDate  options:0];

int months = [conversionInfo month];
int days = [conversionInfo day];
int hours = [conversionInfo hour];
int minutes = [conversionInfo minute];
Run Code Online (Sandbox Code Playgroud)

这非常有用 - 尤其是在格式化字符串时,例如:

[NSString stringWithFormat:@"%d months , %d days, %d hours, %d min", months, days, hours, minutes];
Run Code Online (Sandbox Code Playgroud)

快乐编码:)

  • NSHourCalendarUnit已更改为NSCalendarUnitHour.与分钟,天,月相同.猜猜那天苹果工程师正处于破解状态. (3认同)

kvi*_*ver 25

NSDate参考是一个很棒的小文档:http: //developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
Run Code Online (Sandbox Code Playgroud)

如果你想要时间间隔差异,你正在寻找什么.

几天(因为不是每天都有相同的分钟数,小时数)你想看到Martins在下面回答并使用NSDateComponents和[NSCalendar currentCalendar]