我使用日期时间选择器来获取两个NSDates . 现在我想计算这两个NSDates之间的天数 . 如何找到两个NSDates之间的区别 .
请给我一些解决方案 .
非常感谢 .
NSDate参考是一个很棒的小文档:http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
如果你想要时间间隔差异,你正在寻找什么 .
几天(因为不是每天都有相同的分钟数,小时数)你想看到Martins在下面回答并使用NSDateComponents和[NSCalendar currentCalendar]
这里有一个小宝石 - 不仅仅是几天:
// 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];
这非常有用 - 尤其是在格式化字符串时,例如:
[NSString stringWithFormat:@"%d months , %d days, %d hours, %d min", months, days, hours, minutes];
快乐编码:)
这是一个Swift实现(我在调试诸如网络请求和JSON解析之类的东西时一直使用它):
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))
3 回答
NSDate参考是一个很棒的小文档:http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
如果你想要时间间隔差异,你正在寻找什么 .
几天(因为不是每天都有相同的分钟数,小时数)你想看到Martins在下面回答并使用NSDateComponents和[NSCalendar currentCalendar]
这里有一个小宝石 - 不仅仅是几天:
这非常有用 - 尤其是在格式化字符串时,例如:
快乐编码:)
这是一个Swift实现(我在调试诸如网络请求和JSON解析之类的东西时一直使用它):