2011-04-24 40 views
1

我正在计算我的地址簿中的任何联系人是否在未来10天内有生日。有很多代码可以比较日期,但我只想比较日期和月份。例如,如果一个联系人在05/01/1960出生(假设今天是2011年4月24日),那么我只想计算一下,直到他们的生日只有六天。帮助赞赏。我的联系人在未来10天内的生日

+0

在SO上做你的CS作业会留下很长的纸痕迹......祝你好运。 – coneybeare 2011-04-24 18:44:58

回答

4

将生日更改为今年(或明年如果生日已在今年),并使用NSDateComponents和NSCalendar进行计算。

看起来有点复杂,但你可以做这样的:

NSDate *birthDay = ... // [calendar dateFromComponents:myBirthDay]; 

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; 

NSDateComponents *thisYearComponents = [calendar components:NSYearCalendarUnit fromDate:[NSDate date]]; 
NSDateComponents *birthDayComponents = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:birthDay]; 
[birthDayComponents setYear:[thisYearComponents year]]; 

NSDate *birthDayThisYear = [calendar dateFromComponents:birthDayComponents]; 

NSDateComponents *difference = [calendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:birthDayThisYear options:0]; 
if ([difference day] < 0) { 
    // this years birthday is already over. calculate distance to next years birthday 
    [birthDayComponents setYear:[thisYearComponents year]+1]; 
    birthDayThisYear = [calendar dateFromComponents:birthDayComponents]; 
    difference = [calendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:birthDayThisYear options:0]; 
} 


NSLog(@"%i days until birthday", [difference day]); 
+0

太棒了!感谢fluchtpunkt。这工作完美。谁会想到这么简单就需要这么多的工作。 – Jeremy 2011-04-24 18:39:24

+0

与日期相关的一切都需要大量的代码,如果你想做正确的话。这就是为什么有很多时区,夏令时,闰年等错误。 (是的,我看你86400用户。)我们可以感到高兴,我们有NSDateComponents和NSCalendar,否则你可能需要20倍的代码。 – 2011-04-24 18:47:14

+0

哦,顺便说一句,即使你认为你对未来几年的生日不感兴趣,也不要删除'if([difference day] <0)'部分。其实你对一年中前10天的生日至少有一年的最后10天感兴趣。花了我一段时间来弄清楚这一点。 – 2011-04-24 18:50:05

0

您的联系NSDate使用下面的NSDate功能。

- (NSTimeInterval)timeIntervalSinceNow 

上述函数返回在接收器和当前日期和时间之间的间隔。

NSTimeInterval interval = [date1 timeIntervalSinceNow:myContactDate]; 

NSTimeInterval是以秒计的经过时间(表示为浮点数)。然后你可以除以86400,这是一天中的秒数和四舍五入到最接近的整数。

NSInteger days = interval/86400; 

现在你有天数...

编辑:

您也可以使用NSCalendarNSDateComponents只得到两个日期之间的天组件。

- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts 

使用下面的代码作为参考。 (Taken From Apple Documentation for NSCalendar

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
    NSDate *startDate = ...; 
    NSDate *endDate = ...; 
    unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; 

    NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0]; 
    int months = [comps month]; 
    int days = [comps day]; 
相关问题