如何比较 NSDates 以查找数组中最早和最新的日期?
我的代码在确定数组中最早日期和最晚日期时遇到很多问题。这是我正在使用的代码:
NSDate *startDate = nil; // Earliest date
NSDate *endDate = nil; // Latest date
for (id entry in myArray)
{
NSDate *date = [entry objectForKey:kDate];
if (startDate == nil && endDate == nil)
{
startDate = date;
endDate = date;
}
else if ([date compare:endDate] == NSOrderedAscending)
{
startDate = date;
}
else if ([date compare:startDate] == NSOrderedDescending)
{
endDate = date;
}
date = nil;
}
请有人帮我找出哪里出错了?
I'm having a lot of problems with my code that determines the earliest date and latest date in an array. Here is the code I'm using:
NSDate *startDate = nil; // Earliest date
NSDate *endDate = nil; // Latest date
for (id entry in myArray)
{
NSDate *date = [entry objectForKey:kDate];
if (startDate == nil && endDate == nil)
{
startDate = date;
endDate = date;
}
else if ([date compare:endDate] == NSOrderedAscending)
{
startDate = date;
}
else if ([date compare:startDate] == NSOrderedDescending)
{
endDate = date;
}
date = nil;
}
Please can someone help me work out where I'm going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您还可以使用
NSDates
与方法对NSArray
进行排序:然后在
[array firstObject]
将是第一个日期(例如 1970-01-01T00:00 :00),最后一个对象:[array lastObject]
将是最后一个日期:(例如 2011-01-12T00:00:00)Also you can sort
NSArray
withNSDates
with method:Then at
[array firstObject]
will be first date (e.g. 1970-01-01T00:00:00), and last object:[array lastObject]
will be last date: (e.g. 2011-01-12T00:00:00)您肯定在
else if
语句中以错误的方式设置了startDate
和endDate
吗?你不想要这个吗:Surely you're setting
startDate
andendDate
the wrong way round in theelse if
statements? Don't you want this:您还可以使用预定义的
遥远的过去
和distantFuture
常量以避免对nil
进行额外检查:You may also use the pre-defined
distantPast
anddistantFuture
constants to avoid the extra check fornil
:您还可以使用
earlierDate:
和laterDate:
NSDate 函数You could also use the
earlierDate:
andlaterDate:
NSDate functions对于其他类似的问题:我认为
valueForKeyPath:
选项非常简洁:这假设数组中的对象按照您想要的方式实现
compare:
方法。例如,我用它来获取日期数组中的最早日期。如果您想在此处使用它,则数组中的对象应该覆盖compare:
方法。Just for other similar problems: the
valueForKeyPath:
option is very neat I think:This assumes the object in the array implement the
compare:
method the way you want it. I use it to get the earliest date in an array of dates for example. If you would like to use it here, the objects in the array should override thecompare:
method though.最早的日期可以通过使用标准算法来细化数组中的最小/最大值来找到:
要查找数组中的最新日期,请使用 NSOrderedDescending 而不是 NSOrderedAscending。
The earliest date might be found by using the standard algorithm to fine min/max value in array:
To find the latest date in array use
NSOrderedDescending
instead ofNSOrderedAscending
.