简体   繁体   English

两个NSDates之间的差异

[英]Difference between two NSDates

I am taking two NSDates by using date time picker. 我使用日期时间选择器来获取两个NSDates。 Now I want to count the number of days between these two NSDates. 现在我想计算这两个NSDates之间的天数。 How can I find the difference between two NSDates. 如何找到两个NSDates之间的区别。

please give me some solution. 请给我一些解决方案。

Thanks alot. 非常感谢。

Here's a little gem for you - with more than just days: 这里有一个小宝石 - 不仅仅是几天:

// 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];

This is very helpful - especially when formatting string such as: 这非常有用 - 尤其是在格式化字符串时,例如:

[NSString stringWithFormat:@"%d months , %d days, %d hours, %d min", months, days, hours, minutes];

Happy Coding :) 快乐编码:)

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

- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate

is what you are looking for if you want time interval difference. 如果你想要时间间隔差异,你正在寻找什么。

For days (as not every day has same number of minutes, hours) you want to see Martins answer below and use NSDateComponents with [NSCalendar currentCalendar] 几天(因为不是每天都有相同的分钟数,小时数)你想看到Martins在下面回答并使用NSDateComponents和[NSCalendar currentCalendar]

Here's a Swift implementation (I use this all the time while debugging things like network requests and JSON parsing): 这是一个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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM