Pergunta

I’d like to set up an NSDate object which can tell me whether a specified date is between two other dates, but disregard year. I have a little something in my app which does something special at Christmas and I’d like to future-proof it for subsequent years. I’m using the following code to check if the current date is between December 1st and December 31st, but I’ve had to specify the year (2013).

I’m not too sure how to go about modifying it to work for any year – since the dates are converted into plain numeric values, can it even be done?

+ (NSDate *)dateForDay:(NSInteger)day month:(NSInteger)month year:(NSInteger)year
{
    NSDateComponents *comps = [NSDateComponents new];
    [comps setDay:day];
    [comps setMonth:month];
    [comps setYear:year];
    return [[NSCalendar currentCalendar] dateFromComponents:comps];
}

- (BOOL)laterThan:(NSDate *)date
{
    if (self == date) {
        return NO;
    } else {
        return [self compare:date] == NSOrderedDescending;
    }
}

- (BOOL)earlierThan:(NSDate *)date
{
    if (self == date) {
        return NO;
    } else {
        return [self compare:date] == NSOrderedAscending;
    }
}
Foi útil?

Solução

It sounds like all you need to be able to do is determine if an NSDate falls in December. I believe you can do it like this:

NSDate * now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *nowComponents = [gregorian components:NSMonthCalendarUnit fromDate:now];
if ([nowComponents month] == 12) {
    // It's December, do something
}

If you don't want to be limited to an entire month you could get the month and day components of your current date.

Outras dicas

To tell if a date is later in the year than some given date I'd use something like this:

// yearlessDate is in the form MMddHHmmss
+BOOL date:(NSDate*)theDate isLaterInYearThan:(NSString*)yearlessDate {
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"MMddHHmmss";
    NSString* theDateFormatted = [fmt stringFromDate:theDate];
    return [theDateFormatted compareTo:yearlessDate] == NSOrderedDescending;
}

The usual caveats apply re timezone, 12/24 device setting, etc. It would be most optimal to make the DateFormatter a static object.

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