我使用以下代码来比较两个日期,我希望代码返回" 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");
}
答案 0 :(得分:2)
那是因为你的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
希望这有帮助