I want to test if a date in the past is going to have a "birthday" between 2 dates in the future. Think of it just as a birthday. What I have at the moment:
The whole bit with splitting the date into components and tweaking the year to be this year is pretty nasty. I will have obvious problems around the new year as well even if I was to get the current year properly.
How should I go about comparing 2 dates like this as if they were a birthday? From what I can understand using NSDate to compare I can only compare fixed time stamps.
I have been looking in to NSCalendar for comparing as well but it seems like you can only get components out of it. Easy to get the age in years but difficult to do what I want. I have also tried to just ask the date for the month and day component and then create a new date out of it but that gives me a year of 0001.
Code:
// NSDate myDate is a date in the past - like 27 jul 1987
// NSDate fromDate - in the future - 20 Jul 2011.
// NSDate toDate - in the future - 30 Jul 2011.
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:units fromDate:myDate];
[components setYear:2011]; // <- This is the hack I want to get rid of.
NSDate *yearCorrected = [calendar dateFromComponents:components];
if (([yearCorrected compare:fromDate] != NSOrderedAscending) && ([yearCorrected compare:toDate] != NSOrderedDescending)) {
NSLog(@"birthday!");
The whole bit with splitting the date into components and tweaking the year to be this year is pretty nasty. I will have obvious problems around the new year as well even if I was to get the current year properly.
How should I go about comparing 2 dates like this as if they were a birthday? From what I can understand using NSDate to compare I can only compare fixed time stamps.
I have been looking in to NSCalendar for comparing as well but it seems like you can only get components out of it. Easy to get the age in years but difficult to do what I want. I have also tried to just ask the date for the month and day component and then create a new date out of it but that gives me a year of 0001.