检查NSDate是否在下周

时间:2016-08-17 01:50:17

标签: objective-c nsdate

我尝试了以下代码,但我没有得到User-agent: * 下周的情况。我怎么知道函数中的date参数是下周的?以下代码始终返回1.

date

2 个答案:

答案 0 :(得分:1)

提取日期组件时需要传递NSCalendarUnitWeekOfYear

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todaysComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents = [gregorian NSCalendarUnitWeekOfYear fromDate:date];
NSUInteger datesWeek = [otherComponents weekOfYear];

答案 1 :(得分:0)

使用datecomponents进行周计算会在日期接近年末时给出问题,即"一年中的第一周被指定为包含一年中第一个星期四的一周。 (ISO 8601)"

我觉得比较某些粒度的日期更容易,在这种情况下是每周一次(以下代码检测过去,上周,本周,下周或未来的日期是否超过一周)< / p>

-(EventWeekRange)numberOfWeeksFromTodayToEvent:(NSDate *)eventDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSComparisonResult comparison = [calendar compareDate:[NSDate date] toDate:eventDate toUnitGranularity:NSCalendarUnitWeekOfYear];
    if (comparison == NSOrderedSame) {
        return RangeThisWeek;
    } else if (comparison == NSOrderedAscending) { // The event date is in the future
        // Advance today's date one week to check if this new date is in the same week as the event
        NSDate *todaysNextWeek = [[NSDate date]dateByAddingTimeInterval:60*60*24*7];
        if ([calendar compareDate:todaysNextWeek toDate:eventDate toUnitGranularity:NSCalendarUnitWeekOfYear] == NSOrderedSame) {
            return RangeNextWeek;
        } else {
            return RangeLater;
        }
    } else { // The event date is in the past
        // Advance the event's date one week to check if this new date is in the same week as today
        NSDate *eventsNextWeek = [eventDate dateByAddingTimeInterval:60*60*24*7];
        if ([calendar compareDate:eventsNextWeek toDate:[NSDate date] toUnitGranularity:NSCalendarUnitWeekOfYear] == NSOrderedSame) {
            return RangeLastWeek;
        } else {
            return RangeEarlier;
        }
    }
}