2010-02-13 89 views
11

我試圖強制用戶選擇一個日期在未來與日期選擇器。我顯然使用了compare方法,但是,當我執行下面的代碼時,即使它與[NSDate date]的日期相同,它也會告訴執行if語句。這裏是我的代碼:比較NSDate [NSDate日期]

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

您是否嘗試過使用'laterDate:'(或'earlierDate:')做比較? – gerry3 2010-02-13 19:25:20

+0

如果你NSLog日期只是爲了看看它是否有正確的值,會發生什麼。 – 2010-02-13 19:43:10

回答

15

我不知道答案,你的問題,但你怎麼能繞過它。

只需使用的UIDatePickerminimumDate屬性,甚至更清潔的方式。

+0

這工作得很好,沒有看到在UIDatePicker的API,謝謝。 – skylerl 2010-02-13 19:45:31

24

您可以使用

[datePicker.date timeIntervalSinceNow] 

返回一個NSTimeInterval(只是一個雙一個typedef,以秒爲單位),這是積極的未來和負過去。

正如醫生說,比較提供亞秒級的比較,這樣你就可以(在未來,而不只是某個時候)用它來強迫日期以後要一整天。

1

一個NSDate對象同時包含日期和時間,所以有與之前或其他日期的同一天后落在同一天MANY日期。

date類方法返回與當前日期的日期和時間的日期的對象。