计算ios中两个日期(查找即将到来/过去的生日)之间的持续时间

时间:2016-04-25 11:32:15

标签: ios objective-c nsdate

如何计算两个日期之间的持续时间。像enter image description here enter image description here 我从联系人框架获取联系人生日列表。现在我想将今天的日期与用户DOB值进行比较,我应该显示"剩余天数"(生日)。

例如: 在联系人中,我添加了一个用户:DOB:dd / MM / yyyy - > 12/04/1960

今天的日期是:2016年4月25日

我想获得即将到来的生日日期(两个日期之间的持续时间)

o / p: 18天

我怎样才能得到这个

2 个答案:

答案 0 :(得分:3)

尝试以下代码行。你会得到解决方案。

NSDateComponents *components;
NSInteger days;

components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit 
    fromDate: startDate toDate: endDate options: 0];
days = [components day];

答案 1 :(得分:0)

使用以下

unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit |     NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *conversionInfo = [currCalendar components:unitFlags fromDate:fistDate   toDate:secondDate  options:0];
int months = [conversionInfo month]; // to get number of months
int days = [conversionInfo day]; //  to get number of days
int hours = [conversionInfo hour]; // to get hour difference
int minutes = [conversionInfo minute]; // to get hour difference

Difference between two NSDates

复制