Pergunta

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

Foi útil?

Solução

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.

Outras dicas

+(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've checked existence of all days from January 1st, 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

It is still faster just to check the components.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top