Objective C ,比较两个日期
我正在尝试比较两个日期,但我根本看不到它是如何工作的...
这是我正在使用的代码:
NSCalendar* myCalendar = [NSCalendar currentCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:[NSDate date]];
[components setYear:2012];
[components setMonth:03];
[components setDay:25];
NSDate *startDate = [myCalendar dateFromComponents:components];
NSDateComponents* components2 = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:[NSDate date]];
[components2 setYear:2012];
[components2 setMonth:04];
[components2 setDay:25];
NSDate *endDate = [myCalendar dateFromComponents:components];
NSComparisonResult result1 = [now compare:startDate];
NSComparisonResult result2 = [now compare:endDate];
if (result2 &&
result1
) {
int x =1;
}
问题是即使这两个日期是将来的日期,我仍然可以进入 if 条件……有什么理由吗?
I am trying to compare two dates but I can t see how it works at all ...
this is the code that I am using :
NSCalendar* myCalendar = [NSCalendar currentCalendar];
NSDateComponents* components = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:[NSDate date]];
[components setYear:2012];
[components setMonth:03];
[components setDay:25];
NSDate *startDate = [myCalendar dateFromComponents:components];
NSDateComponents* components2 = [myCalendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:[NSDate date]];
[components2 setYear:2012];
[components2 setMonth:04];
[components2 setDay:25];
NSDate *endDate = [myCalendar dateFromComponents:components];
NSComparisonResult result1 = [now compare:startDate];
NSComparisonResult result2 = [now compare:endDate];
if (result2 &&
result1
) {
int x =1;
}
the thing is even if the two dates are in the future , i still can get into the if condition ... any reason ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
result1 和 result2 的值是以下之一。
唯一一次 (result2 && result1) 不会返回 true 的情况是其中一个日期的计算结果为 false 或 0。仅当其中一个日期与现在完全相同时才会发生这种情况。
The values of result1 and result2 are one of the following.
The only time (result2 && result1) wouldn't return true is when one of them evaluates to false or 0. This only happens if one of the dates is exactly the same as now.
NSComparisonResult
不是布尔值。 请参阅文档。根据您想要的输入方式,您应该检查NSOrderedAscending
(现在更早)、NSOrderedSame
(相同日期)或NSOrderedDescending
>(现在是以后)。An
NSComparisonResult
is not a boolean. See the documentation. Depending on how you want to if to be entered, you should check forNSOrderedAscending
(now is earlier),NSOrderedSame
(same dates), orNSOrderedDescending
(now is later).试试这个。
NSComparisonResult
这些常量用于指示请求中的项目如何排序。
try this.
NSComparisonResult
These constants are used to indicate how items in a request are ordered.
通过使用此函数,您可以比较两个日期。这是经过测试的函数,在我这边运行良好。
}
By using this function you can compare two dates.This is tested function and working fine on my end.
}