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){
我正在尝试检索当前时间并将其与输入时间进行比较。这是我现在的代码的一部分(iOS的目标c),但NSTimeInterval导致断点。作为对此的补充,我还想将日期纳入比较中,因此如果是在星期二下午5:00之后会发生事件。因此,如果您对如何合并它有任何想法,将不胜感激!
答案 0 :(得分:2)
比较两个日期:
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");
}
这可以解决你的问题。
答案 1 :(得分:0)
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;
}