Primary Data Filter Until Today

I had problems with this and I did not find the right answer for SO, so I will leave a little tutorial here.

The goal is to filter selected objects by today's date.

Note. Compatible with Swift 3.

+4
source share
2 answers

You cannot just compare date and date:

let today = Date()
let datePredicate = NSPredicate(format: "date == %@", today)

This will not show anything, since it is unlikely that your date is the EXACT date of the comparison (it includes seconds and milliseconds)

The solution is this:

// Get the current calendar with local time zone
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local

// Get today beginning & end
let dateFrom = calendar.startOfDay(for: Date()) // eg. 2016-10-10 00:00:00
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute],from: dateFrom)
components.day! += 1
let dateTo = calendar.date(from: components)! // eg. 2016-10-11 00:00:00
// Note: Times are printed in UTC. Depending on where you live it won't print 00:00:00 but it will work with UTC times which can be converted to local time

// Set predicate as date being today date
let datePredicate = NSPredicate(format: "(%@ <= date) AND (date < %@)", argumentArray: [dateFrom, dateTo])
fetchRequest.predicate = datePredicate

This is by far the easiest and shortest way to display only those objects that have today.

+11
source

Swift4 Lawrence413 can be simplified a bit:

//Get today beginning & end
let dateFrom = calendar.startOfDay(for: Date()) // eg. 2016-10-10 00:00:00
let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom)

component, .

0

Source: https://habr.com/ru/post/1659219/


All Articles