DSmith
DSmith

Reputation: 159

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!

Upvotes: 0

Views: 1111

Answers (2)

Nilesh Jha
Nilesh Jha

Reputation: 1636

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;
         }

Upvotes: 0

John Farkerson
John Farkerson

Reputation: 2632

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.

Upvotes: 2

Related Questions