If statement with dates

前端 未结 5 759
予麋鹿
予麋鹿 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 17:41

    create a NSDate object with the time 8:10 and one with 8:00. Now you can compare the given date with both these dates

    if(([date0800 compare:date] == NSOrderingAscending) && [date0810 compare:date] == NSOrderingDescending) )
    {
        // date is between the other
    }
    

    to create the boundaries dates you can do this

    NSDate *date = [NSDate date]; // now
    NSDateComponents *components = [[NSCalendar currentCalendar] components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit ) fromDate:date];
    components.hour = 8;
    components.minute = 0;
    
    NSDate *date0800 = [[NSCalendar currentCalendar] dateFromComponents: components];
    components.minute = 10;
    NSDate *date0810 = [[NSCalendar currentCalendar] dateFromComponents: components];
    

    if you insist of using operators like < and >, you can use the timeinterval of the date objects.

    if(([date0800 timeIntervalSince1970] < [date timeIntervalSince1970]) && ([date0810 timeIntervalSince1970] > [date timeIntervalSince1970]))
    {
        // date lays between the other two
    }
    

    but beware of checking == on it, as it could be faulty due to rounding errors.

提交回复
热议问题