【问题标题】:NSDate Comparing Two Dates Not WorkingNSDate比较两个日期不起作用
【发布时间】:2018-03-15 14:36:17
【问题描述】:

我正在使用以下代码比较两个日期,我希望代码返回“newDate is less”,因为今天的日期是 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");
    }

【问题讨论】:

标签: ios objective-c nsdate nsdateformatter


【解决方案1】:

那是因为您的 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");
}

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

希望对你有帮助

【讨论】:

  • 是的,但是如果我将日期更改为 15 日,它不会说同样的内容,而是会说 newDate is less
  • @curtis-boylan :正如预期的那样,因为您的今天有时间组件,例如当我现在使用它时,它今天显示为 2018-03-15 15:34:33 +0000 但因为您的日期字符串 2018-03-14 转换为日期时没有时间它变成 2018-03-15 00:00:00 +0000 因为显然今天大于你的 newDate 它说日期更小
  • 有什么办法可以解决这个问题吗?我不想要时间组件
猜你喜欢
  • 1970-01-01
  • 2012-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
相关资源
最近更新 更多