Vladislav
Vladislav

Reputation: 1502

Get elements from array where date is today

I have an array of objects where a property is date of type 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.

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 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?

Upvotes: 0

Views: 791

Answers (3)

vadian
vadian

Reputation: 285069

You can filter all dates which are today with the filter function and isDateInToday of NSCalendar

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

Upvotes: 0

Alexander Doloz
Alexander Doloz

Reputation: 4188

One-liner:

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

Upvotes: 1

Wain
Wain

Reputation: 119031

You can use NSDateComponents to create the dates which represent the start and end of your acceptable range. 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. This will generate a filtered array for you.

You could use isDateInToday to filter the content too.

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.

Upvotes: 0

Related Questions