How to compare time

后端 未结 6 645
逝去的感伤
逝去的感伤 2020-12-10 07:13

How to compare time in Objective C?

if (nowTime > 9:00 PM) && (nowTime < 7:00 AM) 
{
  doSomething;
}
6条回答
  •  生来不讨喜
    2020-12-10 07:59

    If anybody needs, this is a code to create sections in a tableView according to the date of objects.

    Method to get dates for today, yesterday, etc. (taken from ReMail project DateUtil class):

    #define DATE_UTIL_SECS_PER_DAY 86400
    
    -(void)refreshData {
        //TODO(gabor): Call this every hour or so to refresh what today, yesterday, etc. mean
        NSCalendar *gregorian = [NSCalendar currentCalendar];
        self.today = [NSDate date];
        self.yesterday = [today dateByAddingTimeInterval:-DATE_UTIL_SECS_PER_DAY];
        self.lastWeek = [today dateByAddingTimeInterval:-6*DATE_UTIL_SECS_PER_DAY];
        self.todayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:today];
        self.yesterdayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:yesterday];
        self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
    }
    

    Method to sort tableData for table view sections according to date:

    // Sort tableData objects according to the date
        for (MCMessage *mcMessage in self.tableData) {
            NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:mcMessage.dateTime];
            NSInteger day = [components day];
            NSInteger month = [components month];
            NSInteger year = [components year];
    
            NSLog(@"Day:%d, Month:%d, Year:%d. Today day:%d. Yesterday:%d", day, month, year, dateUtil.todayComponents.day, dateUtil.yesterdayComponents.day);
    
            if ((dateUtil.todayComponents.day == day) && (dateUtil.todayComponents.month == month) && (dateUtil.todayComponents.year == year))
            {
                [self.todayData addObject:mcMessage];
            }
            else if ((dateUtil.yesterdayComponents.day == day) && (dateUtil.yesterdayComponents.month == month) && (dateUtil.yesterdayComponents.year == year))
            {
                [self.yesterdayData addObject:mcMessage];
            }
            else
            {
                [self.soonerData addObject:mcMessage];
            }
        }
    

提交回复
热议问题