将NSDate与[NSDate日期]进行比较

时间:2010-02-13 19:15:56

标签: iphone datepicker compare nsdate uidatepicker

我试图强制用户使用日期选择器选择将来的日期。我显然使用了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];
}

3 个答案:

答案 0 :(得分:24)

您可以使用

[datePicker.date timeIntervalSinceNow]

返回一个NSTimeInterval(只是一个double的typedef,以秒为单位),对于未来是正面的,对过去是负面的。

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

答案 1 :(得分:15)

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

只需使用 UIDatePicker minimumDate 属性,即使是更清晰的方法。

答案 2 :(得分:1)

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

date类方法返回一个日期对象,其中包含当前日期和时间。

相关问题