简体   繁体   中英

Compare current date and time iOS

NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                         [dateFormatter setDateFormat:@"hh:mm"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
NSDate* firstDate = [dateFormatter dateFromString:resultString];
NSDate* secondDate = [dateFormatter dateFromString:@"16:00"];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];

if (timeDifference < 0){

I'm trying to retrieve the current time and compare it with an input time. This is part of my code as of now (objective c for iOS), but NSTimeInterval causes a breakpoint. As an addition to this I would also like to incorporate the date into the comparison, so if it's after 5:00pm on Tuesday an event would occur. So if you have any ideas on how to incorporate that as well it would be greatly appreciated!

To compare two dates:

if ([firstDate compare:secondDate] == NSOrderedDescending) {
    NSLog(@"firstDate is later than secondDate");
    NSTimeInterval timeDifference = [firstDate timeIntervalSinceDate:secondDate];
} else if ([firstDate compare:secondDate] == NSOrderedAscending) {
    NSLog(@"firstDate is earlier than secondDate");
    NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
} else {
    NSLog(@"firstDate and secondDate are the same");
}

This should solve your problems.

NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                         [dateFormatter setDateFormat:@"hh:mm"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
NSDate* firstDate = [dateFormatter dateFromString:resultString];
NSDate* secondDate = [dateFormatter dateFromString:@"16:00"];
 NSComparisonResult result = [secondDate compare:firstDate];
        switch(result){
            case NSOrderedDescending:
                NSLog(@"date1 is later than date2");
                break;
            case NSOrderedAscending:
                NSLog(@"date1 is earlier than date2");
                break;
            default:
                NSLog(@"dates are the same");
                break;
         }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM