How to check if a specific date exists?

How can I check if a specific 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 only get March 1st. I cannot find a function that allows this, the only way I can do this is to check after creating the NSDate if the components are consistent with what I ordered

+4
source share
2 answers

You can use the method -[NSDateFormatter dateFromString:] :

 + (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 .

+8
source
 +(BOOL)dateExistsYear:(int)year month:(int)month day:(int)day{ NSDateComponents *components = [[NSDateComponents alloc] init]; [components setYear:year]; [components setMonth:month]; [components setDay:day]; NSDate *date = [[NSCalendar currentCalendar] dateFromComponents:components]; [components release]; components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date]; if([components year] != year || [components month] != month || [components day] != day){ return NO; } else{ return YES; } } 

I checked the existence of all days from January 1, 2000 to December 12, 2012.

  2011-04-28 11: 42: 57.130 Test [1543: 903] interval 1.103822 // using the above function  
 2011-04-28 11: 42: 59.498 Test [1543: 903] interval 2.367271 // using dateformatter

Check components even faster.

+4
source

All Articles