将 NSDate 与 [NSDate 日期] 进行比较
我试图强制用户使用日期选择器选择未来的日期。我显然使用了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];
}
I am trying to force a user to select a date in the future with a date picker. I obviously used the compare: method, however, when I do the following code, even if it's the same date as [NSDate date], it tells the executes the if statement. Here is my code:
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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
它返回一个 NSTimeInterval (只是 double 的 typedef,以秒为单位),它对于未来为正值,对于过去为负值。
正如文档所说,比较提供亚秒级比较,因此您可以使用它来强制他们的日期晚一整天(而不是仅仅在未来的某个时间)。
You can use
which returns an NSTimeInterval (just a typedef for a double, in units of seconds) which is positive for the future and negative for the past.
As the doc says, compare provides subsecond comparison, so you can use this to force their date to be a full day later (instead of just sometime in the future).
我不知道你的问题的答案,但你如何规避它。
只需使用 UIDatePicker 的 minimumDate 属性,这甚至是一种更简洁的方法。
I don't know the answer to your problem, but how you could circumvent it.
Just use the minimumDate property of the UIDatePicker, that's even a much cleaner approach.
NSDate 对象同时包含日期和时间,因此同一天的许多日期可能位于同一天的另一个日期之前或之后。
date
类方法返回一个包含当前日期和时间的日期对象。An NSDate object contains both a date AND a time, so there are MANY dates with the same day that can fall before or after another date with the same day.
The
date
class method returns a date object with the current date day AND time.