gpt4 book ai didi

objective-c - 计算下一个生日日期

转载 作者:行者123 更新时间:2023-12-03 16:54:47 27 4
gpt4 key购买 nike

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

最佳答案

这是我的做法。

请注意,在本例中,您选择的日期是闰日,因此结果将显示非闰年年份中的第二天。 “正常”日期将显示新年的同一天。

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

关于objective-c - 计算下一个生日日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14107400/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com