问题
i'm trying to get date from UIDatePicker (MM-dd format) and to check if its in the range of two other dates;
i have tried it in so many different ways and i think my mind has gone to far :) can someone help me do it as simple as it should be?
this is my last try code:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM-dd"];
NSString *theDate = [dateFormat stringFromDate:birthdateSelector.date];
NSDate *birthdate = [dateFormat dateFromString:theDate];
NSString *Capricorn_Start = @"12-22" ;
NSString *Capricorn_End = @"01-19" ;
if ([birthdate laterDate:[dateFormat dateFromString:Capricorn_End]] && [birthdate earlierDate:[dateFormat dateFromString:Capricorn_Start]]){
NSLog(@"im capricorn");
}
Thanks, Amir.
回答1:
If you have dateA, dateB and dateC, and you want to check if dateA < dateB < dateC, you can get the difference between dateA-dateB and dateB-dateC which will give you diffX and diffY. If diffX sign is equal than diffY sign, it will mean that dateB is between A and C.
Or, in other words, your code would look like this:
NSTimeInterval diffX = [dateB timeIntervalSinceDate:dateA];
NSTimeInterval diffY = [dateC timeIntervalSinceDate:dateB];
if (signbit(diffX) == signbit(diffY))
{
// dateB is in-between dateA and dateC
}
回答2:
Methods laterDate
and earlierDate
return an NSDate
.
You should use instead compare: and check the return value.
回答3:
You can add a year (the same one for both) and then get the time from 1970 for instance and then do your comparisons.
来源:https://stackoverflow.com/questions/9807370/how-to-check-if-date-from-date-picker-is-between-two-other-dates-objective-c