Comparing two dates with nsdate

后端 未结 3 1024
终归单人心
终归单人心 2021-01-26 01:34

In my app I have to compare two times: current (which is 12:44) and given I tried:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatte         


        
相关标签:
3条回答
  • 2021-01-26 01:41

    it means that in your case, neededDate is always higher than the current date. this is probably because you store a 48 hour string in a 24 hour format. change the string to HH:mm

    also, verify the value you store in neededDate.

    here's a small example

    NSDate *neededDate = [[NSDate date] dateByAddingTimeInterval:5];
        if ([neededDate compare:[NSDate date]] == NSOrderedAscending) {
            NSLog(@"asc");
        } else {
            NSLog(@"dec");
        }
    

    in this case, dec will be printed.

    0 讨论(0)
  • 2021-01-26 01:49

    I think the problem is here:

    [dateFormatter setDateFormat:@"hh:mm"];
    

    should be:

    [dateFormatter setDateFormat:@"HH:mm"];
    

    because now for "14:45" it returns (null) date

    (this is additionally to previous answer :)

    0 讨论(0)
  • 2021-01-26 01:55

    Because your neededDate will be equal to "1970/01/01 14:45".

    You need to set correct year and date.

    You can get current year, month and say, for example, using next approach:

    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
    NSLog(@"Current year: %d", components.year);
    NSLog(@"Current month: %d", components.month);
    NSLog(@"Current day: %d", components.day);
    
    0 讨论(0)
提交回复
热议问题