Search code examples
cocoansdatenscalendar

How to check if a particular date exists?


how can I check if a particular date exists?. For example, if I do the following:

 NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:2011];
[dateComponents setMonth:2];
[dateComponents setDay:29];

NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
[dateComponents release];

NSLog(@"date: %@", date);

I will just get March 1st. I cannot find a function that allows this, the only way I can do it, is by checking after creating the NSDate if the components agree with what I ordered


Solution

  • You could use the -[NSDateFormatter dateFromString:] method:

    + (BOOL)dateExistsYear:(int)year month:(int)month day:(int)day
    {
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        dateFormatter.dateFormat = @"yyyyMMdd";
    
        NSString* inputString = [NSString stringWithFormat:@"%4d%2d%2d",
                            year,month,day];
    
        NSDate *date = [dateFormatter dateFromString:inputString];
    
        return nil != date;
    }
    

    If you give a valid date, then dateFromString: will succeed, otherwise, it will return nil.