繁体   English   中英

比较当前日期和时间iOS

[英]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){

我正在尝试检索当前时间并将其与输入时间进行比较。 到目前为止,这是我代码的一部分(iOS中的目标c),但是NSTimeInterval会导致断点。 除此之外,我还想将日期纳入比较中,因此,如果在星期二5:00 pm之后会发生一个事件。 因此,如果您对如何将其整合也有任何想法,将不胜感激!

比较两个日期:

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

这应该可以解决您的问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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