简体   繁体   English

从日期为今天的数组中获取元素

[英]Get elements from array where date is today

I have an array of objects where a property is date of type NSDate. 我有一个对象数组,其中属性是NSDate类型的日期。 The array includes future days and past days. 该数组包括将来的日子和过去的日子。

I want to get an array of elements from that array that only includes dates that are in today, not the last 24 hours. 我想从该数组中获取一个元素数组,该数组仅包含今天的日期,而不是过去的24小时。

I ordered the elements by descending (new to old): 我通过降序对元素进行排序(从新到旧):

allDashboards.sortInPlace({ $0.date!.compare($1.date!) == NSComparisonResult.OrderedDescending

I tried to do a for loop, check if date is yesterday and cut the array there, but it doesn't work as it may be no element with a yesterdays date: 我试图做一个for循环,检查日期是否是昨天,然后在那儿剪切数组,但是它不起作用,因为它可能没有昨天的日期:

    for dash in allDashboards {

        if (NSCalendar.currentCalendar().isDateInYesterday(dash.date!)) {
            print(i)
            allDashboards.removeRange(Range.init(start: 0, end: i))
            break
        }

        i += 1
    }

Is there a method to see if date is past a day instead of if the date is part of that day? 有没有一种方法可以查看日期是否超过一天,而不是该日期是否属于该天?

单线:

let todayDashboards = allDashboards.filter { NSCalendar.currentCalendar().isDateInToday($0.date!) }

You can use NSDateComponents to create the dates which represent the start and end of your acceptable range. 您可以使用NSDateComponents创建代表可接受范围的开始和结束的日期。 These can be anything you want. 这些可以是您想要的任何东西。

Once you have those dates, you can create an NSPredicate which matches dates > the start and < the end dates. 拥有这些日期后,您可以创建一个NSPredicate ,以匹配日期>开始日期和<结束日期。 This will generate a filtered array for you. 这将为您生成一个过滤后的数组。

You could use isDateInToday to filter the content too. 您也可以使用isDateInToday来过滤内容。

What you must not do is to iterate the array and mutate it at the same time, which is what your current code does with allDashboards.removeRange inside the for loop. 您必须要做的是同时迭代数组并对其进行变异,这就是您当前的代码对for循环内的allDashboards.removeRangefor

您可以过滤这是今天与所有日期filter功能和isDateInTodayNSCalendar

let filteredDashboards = allDashboards.filter{ NSCalendar.currentCalendar().isDateInToday($0.date!) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM