How to determine if an NSDate is today?

前端 未结 20 2035
礼貌的吻别
礼貌的吻别 2020-11-28 18:20

How to check if an NSDate belongs to today?

I used to check it using first 10 characters from [aDate description]. [[aDate descriptio

20条回答
  •  借酒劲吻你
    2020-11-28 18:49

    for iOS7 and earlier:

    //this is now => need that for the current date
    NSDate * now = [NSDate date];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [calendar setTimeZone:[NSTimeZone systemTimeZone]];
    
    NSDateComponents * components = [calendar components:( NSYearCalendarUnit|    NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: now];
    
    [components setMinute:0];
    [components setHour:0];
    [components setSecond:0];
    
    //this is Today's Midnight
    NSDate *todaysMidnight = [calendar dateFromComponents: components];
    
    
    
    //now timeIntervals since Midnight => in seconds
    NSTimeInterval todayTimeInterval = [now timeIntervalSinceDate: todaysMidnight];
    
    //now timeIntervals since OtherDate => in seconds
    NSTimeInterval otherDateTimeInterval = [now timeIntervalSinceDate: otherDate];
    
    if(otherDateTimeInterval > todayTimeInterval) //otherDate is not in today
    {
        if((otherDateTimeInterval - todayTimeInterval) <= 86400) //86400 == a day total seconds
        {
            @"yesterday";
        }
        else
        {
            @"earlier";
        }
    }
    else
    {
        @"today";
    }
    
    
    now = nil;
    calendar = nil;
    components = nil;
    todaysMidnight = nil;
    
    NSLog("Thank you :-)");
    

提交回复
热议问题