11

我试图强迫用户使用日期选择器选择未来的日期。我显然使用了 compare: 方法,但是,当我执行以下代码时,即使它与 [NSDate date] 的日期相同,它也会告诉执行 if 语句。这是我的代码:

    if ([datePicker.date compare:[NSDate date]] == NSOrderedAscending) // If the picked date is earlier than today
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hmm, this date is earlier than today" 
                                                    message:@"The date you've selected is earlier than today's date, please pick another" 
                                                   delegate:nil  
                                          cancelButtonTitle:@"Okay, I'll pick another" 
                                          otherButtonTitles:nil];
    // Show the alert
    [alert show];

    // Release the alert
    [alert release];
}
4

3 回答 3

24

您可以使用

[datePicker.date timeIntervalSinceNow]

它返回一个 NSTimeInterval (只是一个双精度的 typedef,以秒为单位),对于未来是正数,对于过去是负数。

正如文档所说,比较提供亚秒级比较,因此您可以使用它来强制他们的日期在一天之后(而不是在未来的某个时间)。

于 2010-02-13T19:22:55.300 回答
15

我不知道你的问题的答案,但你怎么能绕过它。

只需使用UIDatePicker的minimumDate属性,这甚至是一种更简洁的方法。

于 2010-02-13T19:32:20.473 回答
1

一个 NSDate 对象同时包含一个日期和一个时间,因此有很多日期在同一天,可以在同一天的另一个日期之前或之后。

date类方法返回具有当前日期日期和时间的日期对象。

于 2010-02-13T19:28:13.457 回答