gpt4 book ai didi

iphone - ios - 查找一周内即将到来的生日

转载 作者:行者123 更新时间:2023-11-29 13:18:03 25 4
gpt4 key购买 nike

我试图在 iOS 上查找一周内即将到来的生日。我从 Facebook 中提取了生日数据并修剪了年份部分(因为根据用户的隐私设置,某些用户可能无法使用它)因此生日数据是一个 NSString,日期格式为 @"MM/dd”

NSDateFormatter *dateFormatter = [[NSDateFormatter dateFormatterWithFormat:@"MM/dd"] retain];
NSDate *today = [NSDate date];
NSDateComponents *todayComponents = [dateFormatter.calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:today];
todayComponents.hour = 13;
todayComponents.minute = 0;
todayComponents.second = 0;
today = [dateFormatter.calendar dateFromComponents:todayComponents];

[facebookFriends enumerateObjectsUsingBlock:^(NSDictionary *friend,
NSUInteger idx,
BOOL *stop) {

NSDate *birthday = [dateFormatter dateFromString:[friend objectForKey:@"birthday"]];
NSDateComponents *birthdayComponents = [dateFormatter.calendar components:NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:birthday];
birthdayComponents.year = todayComponents.year;
birthdayComponents.hour = todayComponents.hour;
birthdayComponents.minute = todayComponents.minute;
birthdayComponents.second = todayComponents.second;

birthday = [dateFormatter.calendar dateFromComponents:birthdayComponents];
NSDateComponents *difference = [dateFormatter.calendar components:NSDayCalendarUnit
fromDate:today
toDate:birthday
options:0];
if (difference.day >= 0 &&
difference.day < 7) { // 7 days in a week
[birthdaysToShow[difference.day] addObject:friend];
}
}];
[dateFormatter release];

其中 dateFormatterWithFormat:NSDateFormatter 上的一个类别:

+ (NSDateFormatter *)dateFormatterWithFormat:(NSString *)formatString
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
dateFormatter.calendar = calendar;
dateFormatter.dateFormat = formatString;
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];

return [dateFormatter autorelease];
}

这里有2个问题:

1-我在这段代码中有一个错误,如果距离新年不到一周,我将无法在新年显示生日,因为我将生日年份设置为对于新年的生日,当前年份和 difference.day 将远小于 0。我该如何解决这个问题?

2- 正如您从上面的代码片段中看到的那样,我正在跳很多舞:首先我使用 [NSDate date] 获取今天的日期和时间,然后我将它撕成它的组件并将它组装回一个 NSDate 中午时间而不是当前时间。我这样做的原因是,如果 [NSDate date] 返回一个时间为 23:00:00 的日期,并且生日时间为 00:00:00(1 小时后,意味着生日是明天),那么 difference.day 等于 0 而不是所需的 1。我在上面的代码片段中所做的是正确的做法吗?我想我可能为看似简单的事情做了太多工作,你如何解决这种安排,这样我就不必将 todaybirthday 分成组件和将它们放回到 NSDate 中?

最佳答案

为每个 birthdayComponents 对象设置正确的年份:

birthdayComponents.year=todayComponents.year; //default

if(birthdayComponents.month< todayComponents.month) birthdayComponents.year=todayComponents.year+1; //their next birthday is next year.

if(birthdayComponents.month==todayComponents.month && birthdayComponents.day<todayComponents.day) birthdayComponents.year=todayComponents.year+1; //their next birthday is next year

关于iphone - ios - 查找一周内即将到来的生日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143633/

25 4 0