Reputation: 3616
Is there a way to check if NSDate object is in the range of month day with out having a year set in range. For example I have NSDate eqaual to February 2 1956 and I want find out if that date is in range between January 10 and February 10 within any year.
Thank you in advance!
Upvotes: 0
Views: 187
Reputation: 1611
You can use NSDateComponents for this
NSDate *date = [NSDate date];
// setting units we would like to use in future
unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
// creating NSCalendar object
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// extracting components from date
NSDateComponents *components = [calendar components:units fromDate:date];
if (components.month <= 2 && components.month >= 1) {
if (components.month == 2) {
if (components.day <= 10) {
// Date is in range
}
} else if (components.month == 2) {
if (components.day >= 10) {
// Date is in range
}
}
Upvotes: 0
Reputation: 3208
Use NSCalendar
and NSDateComponents
.
e.g.
// Assuming 'data' is a valid NSDate object
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit+NSDayCalendarUnit fromDate:date];
NSInteger day = components.day;
NSInteger month = components.month;
if ( (month>=startMonth && month<=endMonth) && (day>=startMonthDay && day<=endMonthDay)) {
// do your stuff
}
Upvotes: 1
Reputation: 55563
You should use NSDate's -compare
message, or, use -timeIntervalSince1970
NSDate *startRange;
NSDate *endRange;
// method one
if (([myDate compare:startRange] > 0) && ([myDate compare:endRange] < 0))
{
// execute code here
}
// method two
if (myDate.timeIntervalSince1970 > startRange.timeIntervalSince1970 &&
myDate.timeIntervalSince1970 < endRange.timeIntervalSince1970)
{
// execute code here
}
Upvotes: 1
Reputation: 3851
You can get the current NSCalendar instance and use the components:forDate: method, then extract the month and date components from the resulting NSDateComponents object.
Upvotes: 0