如何比较NSDates以查找数组中的最早和最晚日期?

时间:2012-01-12 18:00:57

标签: iphone objective-c nsdate

我的代码存在很多问题,这些问题决定了数组中最早的日期和最新日期。这是我正在使用的代码:

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;
}

请有人帮我解决我出错的地方吗?

6 个答案:

答案 0 :(得分:11)

此外,您可以使用NSArray方法对NSDates进行排序:

array = [array sortedArrayUsingSelector:@selector(compare:)];

然后在[array firstObject]将是第一个日期(例如1970-01-01T00:00:00),最后一个对象:[array lastObject]将是最后日期:(例如2011-01-12T00:00 :00)

答案 1 :(得分:7)

您肯定在startDate声明中以错误的方式设置endDateelse if?你不想要这个:

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;
    }
    if ([date compare:startDate] == NSOrderedAscending)
    {
        startDate = date;
    }
    if ([date compare:endDate] == NSOrderedDescending)
    {
        endDate = date;
    }

    date = nil;
}

答案 2 :(得分:3)

您还可以使用预定义的distantPastdistantFuture常量来避免额外检查nil

NSDate *startDate = [NSDate distantFuture];
NSDate *endDate = [NSDate distantPast];

for (id entry in myArray)
{
    NSDate *date = [entry objectForKey:kDate];

    if ([date compare:startDate] == NSOrderedAscending) { startDate = date; }
    if ([date compare:endDate] == NSOrderedDescending)  { endDate = date; }

    date = nil;
}

答案 3 :(得分:2)

您还可以使用earlierDate:laterDate: NSDate函数

NSDate *startDate = [NSDate distantFuture];
NSDate *endDate = [NSDate distantPast];

for (id entry in myArray) 
{
    NSDate *date = [entry objectForKey:kDate];
    startDate = [startDate earlierDate:date];
    endDate = [endDate laterDate:date];
}

答案 4 :(得分:0)

仅针对其他类似问题:我认为valueForKeyPath:选项非常简洁:

[myArray valueForKeyPath:@"@min.self"];
[myArray valueForKeyPath:@"@max.self"];

这假设数组中的对象以您希望的方式实现compare:方法。我用它来获取日期数组中的最早日期。如果您想在此处使用它,则数组中的对象应覆盖compare:方法。

答案 5 :(得分:0)

最早的日期可能是通过使用标准算法对数组中的最小值/最大值进行求值的:

NSMutableArray<NSDate *> *allDates; // dates array
NSDate *earliestDate = allDates.firstObject;
        for (NSDate *date in allDates) {
            if ([date compare:earliestDate] == NSOrderedAscending) {
                earliestDate = date;
            }
        }

要查找数组中的最新日期,请使用NSOrderedDescending而不是NSOrderedAscending