计算下一个生日日期

时间:2013-01-01 02:09:56

标签: objective-c cocoa nsdate

NSDate这样的字符串中计算(并创建)下一个生日@"02/29/1980"的最简单方法是什么? (日/月/年)

3 个答案:

答案 0 :(得分:3)

我将如何做到这一点。

请注意,在这种情况下,您选择的日期是闰日,因此结果将显示非闰年的第二天。 "正常"日期将显示在新的一年的同一天。

NSString *birthdayString        = @"02/29/1980";

// Convert the string to a NSDate
NSDateFormatter *formatter      = [NSDateFormatter new];
formatter.timeZone              = [NSTimeZone timeZoneWithName:@"UTC"];
formatter.dateFormat            = @"MM/dd/yyyy";
NSDate *birthday                = [formatter dateFromString:birthdayString];

// Break the date apart into its components and change the year to the current year
NSCalendar *cal                 = [NSCalendar currentCalendar];
cal.timeZone                    = [NSTimeZone timeZoneWithName:@"UTC"];
NSDate *now                     = [NSDate date];
NSDateComponents *currentComps  = [cal components:NSYearCalendarUnit fromDate:now];
NSDateComponents *birthdayComps = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
                                         fromDate:birthday];
birthdayComps.year              = currentComps.year;

// Create the date from the modified components
NSDate *birthdayDate            = [cal dateFromComponents:birthdayComps];

// Check to see if the birthday has passed yet this year, and if not add one year
if ([now compare:birthdayDate] == NSOrderedDescending)
{
    NSDateComponents *oneYear = [NSDateComponents new];
    oneYear.year = 1;
    birthdayDate = [cal dateByAddingComponents:oneYear toDate:birthdayDate options:0];
}

NSLog(@"Next Birthday: %@", birthdayDate);
// Results: Next Birthday: 2013-03-01

答案 1 :(得分:1)

使用NSDateFormatter将字符串输入日期。然后通过添加一年add a year to it。而鲍勃是你的叔叔。

答案 2 :(得分:0)

简单的方法(闰年被窃听)

 NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit
                                                   fromDate:[NSDate date]
                                                     toDate:birthdate
                                                    options:0];

NSInterger daysLeft = components.day % 365;