Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 575
the Reverend Avatar asked Dec 16 '22 14:12

the Reverend


1 Answers

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.

like image 152
drewag Avatar answered Jan 08 '23 22:01

drewag