[英]Comparing an NSDate to [NSDate date]
我試圖強制用戶使用日期選擇器選擇將來的日期。 我顯然使用了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];
}
您可以使用
[datePicker.date timeIntervalSinceNow]
它返回一個NSTimeInterval(只是一個double的typedef,以秒為單位),它對未來是正面的,對過去是負面的。
正如文檔所說,compare提供亞秒級比較,因此您可以使用它來強制他們的日期為一整天(而不是僅僅是將來的某個時間)。
我不知道你的問題的答案,但你怎么能繞過它。
只需使用UIDatePicker的minimumDate屬性,這甚至是一種更清晰的方法。
NSDate對象包含日期和時間,因此在同一天的另一個日期之前或之后可能會有同一天的許多日期。
date
類方法返回具有當前日期日期和時間的日期對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.