比较NSDate [NSDate日期]
问题描述:
我试图强制用户选择一个日期在未来与日期选择器。我显然使用了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];
}
答
我不知道答案,你的问题,但你怎么能绕过它。
只需使用的UIDatePicker的minimumDate属性,甚至更清洁的方式。
+0
这工作得很好,没有看到在UIDatePicker的API,谢谢。 – skylerl 2010-02-13 19:45:31
答
您可以使用
[datePicker.date timeIntervalSinceNow]
返回一个NSTimeInterval(只是一个双一个typedef,以秒为单位),这是积极的未来和负过去。
正如医生说,比较提供亚秒级的比较,这样你就可以(在未来,而不只是某个时候)用它来强迫日期以后要一整天。
答
一个NSDate对象同时包含日期和时间,所以有与之前或其他日期的同一天后落在同一天MANY日期。
的date
类方法返回与当前日期的日期和时间的日期的对象。
您是否尝试过使用'laterDate:'(或'earlierDate:')做比较? – gerry3 2010-02-13 19:25:20
如果你NSLog日期只是为了看看它是否有正确的值,会发生什么。 – 2010-02-13 19:43:10