检查nsdate是否在其他2 nsdate内,但忽略year

时间:2017-12-14 09:30:53

标签: ios nsdate

我写了这样的代码来检查我的约会是否在其他2个日期之内。

+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate {
    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;

    if ([date compare:endDate] == NSOrderedDescending)
        return NO;

    return YES; 
}

问题是我需要忽略一年。它必须是真实的2017年,2018年等。我该如何重写?

1 个答案:

答案 0 :(得分:0)

使用以下代码将beginDate和endDate的年份更改为日期年份: -

+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate {
    NSUInteger componentFlags = NSCalendarUnitYear|NSCalendarUnitDay|NSCalendarUnitMonth;
     NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:componentFlags fromDate:date];
    NSInteger year = [dateComponents year];


    NSDateComponents *beginDateComponents = [[NSCalendar currentCalendar] components:componentFlags fromDate:beginDate];
    [beginDateComponents setYear:year];
    beginDate = [[NSCalendar currentCalendar] dateFromComponents:beginDateComponents];


    NSDateComponents *endDateComponents = [[NSCalendar currentCalendar] components:componentFlags fromDate:endDate];
    [endDateComponents setYear:year];
    endDate = [[NSCalendar currentCalendar] dateFromComponents:endDateComponents];

    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;

    if ([date compare:endDate] == NSOrderedDescending)
        return NO;

    return YES;
}