我使用日期时间选择器获取了两个NSDate对象。现在,我想要计算这两个NSDate对象之间的天数差异。请问如何找到两个NSDate对象之间的差异。
能否给我一些解决方案。
非常感谢。
我使用日期时间选择器获取了两个NSDate对象。现在,我想要计算这两个NSDate对象之间的天数差异。请问如何找到两个NSDate对象之间的差异。
能否给我一些解决方案。
非常感谢。
这里有一个小技巧 - 不仅可以计算天数:
// 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];
愉快地编程 :)
NSDate reference是一份非常好的文档,涉及IT技术。以下是链接:http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate
以下是一个 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))