未来10天是我联系人的生日

时间:2011-04-24 17:42:26

标签: iphone sdk nsdate date nscalendar

我正在尝试计算我的地址簿的任何联系人是否在接下来的10天内过生日。有足够的代码在线比较日期,但我只想比较日期和月份。例如,如果一个联系人诞生于05/01/1960(假设今天是04/24/2011),那么我只想计算他们的生日只有六天。帮助赞赏。

3 个答案:

答案 0 :(得分: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]);

答案 1 :(得分:0)

检索到联系人的生日后:

ABAddressBook get birthday property

您需要调整年份组件:

NSDate - Changing the year value

然后,您可以计算她生日的天数:

NSDate countdown in days

答案 2 :(得分: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];