繁体   English   中英

NSDate比较两个日期不起作用

[英]NSDate Comparing Two Dates Not Working

我正在使用以下代码比较两个日期,我希望代码返回“ newDate更少”,因为今天的日期是2018-03-16,但是相反,它返回的两个日期是相同的。 有什么办法解决这个问题? 我知道它必须非常简单,只是无法将手指固定在上面。

    NSDateFormatter *dateFormatter=[NSDateFormatter new];
    NSDate *today = [NSDate date]; 
    NSDate *newDate = [dateFormatter dateFromString:@"2018-03-14"]; 

    if([today compare:newDate]==NSOrderedAscending){
        NSLog(@"today is less");
    }
    else if([today compare:newDate]==NSOrderedDescending){
        NSLog(@"newDate is less");
    }
    else{
        NSLog(@"Both dates are same");
    }

那是因为您的newDate为零。 您尚未为dateFormatter指定日期格式。

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; //missing statement in your code
NSDate *today = [NSDate date];
NSDate *newDate = [dateFormatter dateFromString:@"2018-03-14"];

现在它按预期打印输出

编辑1:

由于OP希望在没有任何时间组件的情况下比较日期,因此更新代码以执行相同的操作

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *today = [NSDate date];
NSString *todayString = [dateFormatter stringFromDate:today];
today = [dateFormatter dateFromString:todayString];
NSDate *newDate = [dateFormatter dateFromString:@"2018-03-15"];

if([today compare:newDate]==NSOrderedAscending){
    NSLog(@"today is less");
}
else if([today compare:newDate]==NSOrderedDescending){
    NSLog(@"newDate is less");
}
else{
    NSLog(@"Both dates are same");
}

现在,当新日期指定为newDate is less时,代码显示Both dates are same当新日期指定为newDate is less时显示newDate is less

希望这可以帮助

暂无
暂无

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

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