如何比较今天的日期大于或等于另一个日期

时间:2017-07-09 13:49:10

标签: ios objective-c nsdate nsdateformatter

比较2个日期 if(from_date> =今天&& totime< =今天)  我试过这个

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
NSString * TodayDate = [dateFormatter stringFromDate:[NSDate date]];

if ([displayList.fromTime compare:TodayDate] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");

} else if ([displayList.toTime compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");

} else {
    NSLog(@"dates are the same");

}

2 个答案:

答案 0 :(得分:0)

你并没有说明日期是什么类型的对象,但是因为你将它与今天的字符串进行比较,我假设你比较它们时所有的日期都是字符串?如果是这样,这是一个糟糕的选择。日期比较和字符串比较不一样,会产生不同的结果。

不是将今天的日期变成字符串,而是应该将日期转换为NSDate,然后进行比较。

如果,OTOH,fromDate不是字符串,则表示您的错误。仅仅因为两个对象导致相同的文本被NSLogged并不意味着它们是相同的类型并且可以进行比较,因此请确保它们都是相同的类型(NSDate)然后进行比较。

答案 1 :(得分:0)

您可以比较NSString,这是错误的。您需要比较两个NSDate对象。

这是更新代码:

  NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    // You are doing wrong compareing at here. You need to compare Date nor sting.
//    NSString * TodayDate = [dateFormatter stringFromDate:[NSDate date]];

    NSDate *TodayDate = [NSDate date];
    NSDate *compareData = [dateFormatter dateFromString:@"2017-07-09 11:12:11"];

    if ([compareData compare:TodayDate] == NSOrderedDescending) {
        NSLog(@"date1 is later than date2");

    } else if ([compareData compare:TodayDate] == NSOrderedAscending) {
        NSLog(@"date1 is earlier than date2");

    } else {
        NSLog(@"dates are the same");

    }
相关问题