有没有办法检查NSDate是本周还是下周?

我知道今天是:

[NSDate date]

然后我该怎么办?

最佳答案

使用NSDateComponents,如下所示:

NSCalendar *gregorian = [[NSCalendar alloc]
    initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *today = [NSDate date];

    NSDateComponents *todaysComponents =
        [gregorian components:NSWeekCalendarUnit fromDate:date];

    NSUInteger todaysWeek = [todaysComponents week];


    NSDate *anotherDate = [NSDate date];

    NSDateComponents *otherComponents =
        [gregorian components:NSWeekCalendarUnit fromDate:anotherDate];

    NSUInteger anotherWeek = [otherComponents week];

    if(todaysWeek==anotherWeek){
         NSLog(@"another date is this week");
    }else if(todaysWeek+1==anotherWeek){
         NSLog(@"another date is next week")
    }

您也可以使用其他组件(例如月份或年份)来完全确定。

注意:不要使用timeIntervals。 通过使用NSDateComponents,您可以忽略小时,分钟和秒。我想你想要那个。

08-05 23:05