两个NSDates之间的差异
我通过使用date时间选取器采取两个NSDates。 现在我要计算这两个NSDates之间的天数。 我怎样才能find两个NSDates之间的差异。
请给我一些解决scheme。
非常感谢。
NSDate引用是一个很好的小文档: http : //developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
是你想要的时间间隔差异。
对于天(因为不是每天都有相同的分钟数,小时),你想看到马丁斯答案下面,并使用NSDateComponents与[NSCalendar currentCalendar]
这里有一个gem给你 – 不仅仅是几天:
// 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];
这是非常有用的 – 特别是当格式化string如:
[NSString stringWithFormat:@"%d months , %d days, %d hours, %d min", months, days, hours, minutes];
快乐编码:)
这里有一个Swift实现(我在debuggingnetworking请求和JSONparsing的时候一直使用它):
let date1 = NSDate() // do some long running task let date2 = NSDate() print(date2.timeIntervalSinceDate(date1)) // you can also do this in one line, of course: print(NSDate().timeIntervalSinceDate(date1))