NSDate
从像这样的字符串计算(和创建)下一个生日的最简单方法是@"02/29/1980"
什么?(日月年)
问问题
750 次
3 回答
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
于 2013-01-01T02:42:28.150 回答
1
使用NSDateFormatter将字符串转换为日期。然后通过添加一年来添加一年。鲍勃是你的叔叔。
于 2013-01-01T02:24:22.910 回答
0
简单的方法(闰年被窃听)
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit
fromDate:[NSDate date]
toDate:birthdate
options:0];
NSInterger daysLeft = components.day % 365;
于 2014-11-12T16:22:51.163 回答