How can I filter a Realm List by Date Swift NSPredicates - swift

I want to filter my Realm List by Date. The Filter should show me every listed Item by month. I select the month "June" and the app should show me everything that was sold in June.
this is the code I tried but it obviously doesnt worked out.
let date = Date()
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
let formattedDate = format.string(from: date)
print(formattedDate)
let current = Calendar.current
let componentDate = current.component(.month, from: date)
print(current.component(.month, from: date))
let articles = realm.objects(Article.self).filter("artSoldDate = \(componentDate)")
return articles

You would need to use a date range filter. You would need to start the range at a specific date and end it at a certain date. For example,
let predicate = NSPredicate(format: "artSoldDate >= %# AND artSoldDate <= %#", startDate, endDate)
let result = realm.objects(Art.self).filter(predicate)
Your example seems to try and check when the artSoldDate is exactly some date.

Related

CoreData - How to filter for partial matches?

I am using CoreData for a project - My CoreData entity has an attribute "date", type Date. I am trying to filter the data based on mm/dd/yy only. Here is what I have so far
fetchRequest.predicate = NSPredicate(format: "date = %#", date as! NSDate)
This doesn't work because "date" includes the time, which makes each entry different even though the calendar date is the same.
I have tried parsing the date into a string mm/dd/yy and changing the format to "date CONTAINS stringDate", but that didn't work- I don't think I should be able to search for a string inside a Date.
I have looked through the documentation on predicates, but I cannot figure out how to apply to type Date.
The approach you need to take here is to create a predicate where you test if the date attribute is between the start of the day and at the end of the day so you will get a match for any time of that day.
let predicate = NSPredicate(format: "date >= %# && date <= %#",
argumentArray: [startDate, endDate]
where you calculate the dates from a given date inputDate as
let startDate = Calendar.current.startOfDay(for: inputDate)
let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)!

How to query data that has a timestamp that is less than n hours?

Currently my method for determining wether data is older than n hours uses this code after getting a timestamp from a document:
let timestamp = i.get("timestamp") as! Timestamp
let lastUpdatedDate = timestamp.dateValue()
let currentDate = Date()
let cal = Calendar.current
let components = cal.dateComponents([.hour], from: lastUpdatedDate, to: currentDate)
let diff = components.hour!
Usually this code is executed in a for each loop per each document after getting the documents from firestore.
Is there a way to query data using the field timestamp and checking if it is less than n hours instead?
ref.collection("References").whereField("timestamp", isLessThanOrEqualTo: n hours)
If you want a value to compare it against, you can do:
let date = Date().addingTimeInterval(-4 * 60 * 60)
Or you can do:
let date = Calendar.current.date(byAdding: .hour, value: -4, to: Date())
You may have to convert those to a Timestamp from this Date object, e.g., presumably something like:
let timestamp = Timestamp(date)

Swift: Set custom Date(Day only) in DatePicker

I have two date pickers. Let's say fromDatePicker and untilDatePicker. I set the untilDatePicker to current date (ex: 12/06/17) and I want to set the fromDatePicker into first date of the current month (ex: 01/06/17) but I don't have any idea to set the untilDatePicker.
I have read this question but it's not helped me much.
This is swift3 solution and how you set first day of current month in datePicker , if you need to get first of other month just change date variable with some day from that month
let date = NSDate()
let calendar = NSCalendar.current
let components = calendar.dateComponents([.year,.month], from: date as Date)
let startOfMonth = calendar.date(from: components)
self.datePicker.setDate(startOfMonth!, animated: true)

Core Data Predicate Filter By Today's Date

How can I filter Core Data Managed Objects by their Date attribute in Swift?
The goal is to filter fetched objects by today's date.
You can't simply use to compare your date to today's date:
let today = Date()
let datePredicate = NSPredicate(format: "%K == %#", #keyPath(ModelType.date), today)
It will show you nothing since it's unlikely that your date is the EXACT comparison date (it includes seconds & milliseconds too)
The solution is this:
// Get the current calendar with local time zone
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local
// Get today's 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)
// 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's date
let fromPredicate = NSPredicate(format: "%# >= %K", dateFrom as NSDate, #keyPath(ModelType.date))
let toPredicate = NSPredicate(format: "%K < %#", #keyPath(ModelType.date), dateTo as NSDate)
let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate, toPredicate])
fetchRequest.predicate = datePredicate
It's by far the easiest & shortest way of showing only objects which have today's date.
In swift4, Lawrence413's can be simplify a bit:
//Get today's 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)
It get rid of the component part, makes the code have better readability.
Might be helpful to add to Lawrence413's answer that to filter a list of records with an attribute holding today's date, you could use:
let fromPredicate = NSPredicate(format: "datetime >= %#", dateFrom as NSDate)
let toPredicate = NSPredicate(format: "datetime < %#", dateToUnwrapped as NSDate)
...Where "datetime is the name of the attribute"

Swift NSDate get current date but strip Year, Month, and Day

I am trying to get the current date using swift. I have that taken care of but it gets the year month and day and I really only want the current hour and minute. The reason being is that I am trying to later on compare a created date that only has an hour and minute. I am currently just using this
let currentDate = NSDate()
Thank you
let calendar = Calendar.autoupdatingCurrent
let components = calendar.dateComponents([.hour, .minute], from: Date())
let hour = components.hour
let minute = components.minute