If statement with dates

前端 未结 5 756
予麋鹿
予麋鹿 2021-01-16 17:26

what I am trying to do is make a if statement with dates using greater than less than signs. For some reason only the greater than sign works. Here is my code:



        
5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-16 18:04

    Here you are comparing string objects, with < and >, which does not do what you are expecting. You can use NSDateComponents to get the hour and minute to compare those:

    NSDate *today = [NSDate date];
    
    NSCalendar *gregorian = [[NSCalendar alloc]
    
                         initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components =
    
                    [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit ) fromDate:today];
    
    NSInteger hour = [weekdayComponents hour];
    
    NSInteger minutes = [weekdayComponents minute];
    
    BOOL homeroom = (hour == 8) && (minute < 10);
    

    Or you can create a specific NSDate for 8:10 and 8:00 using NSDateFormater and using the compare: function.

提交回复
热议问题