How do I filter events created for the current date in the Realm swift?
A query in the form of Create == NSDate()
will check exact date equality, which will compare down to the second. If you want to check if a date is between a given interval, like checking if it's on a specific day, regardless of the time of day, you could do a BETWEEN
check:
let dtSource = datasource.filter("Create BETWEEN %@", [firstDate, secondDate]).count
Update:
Here's a full code sample to get all date models for the current day:
import RealmSwift
class Event: Object {
dynamic var date = NSDate()
}
let todayStart = Calendar.current.startOfDay(for: Date())
let todayEnd: Date = {
let components = DateComponents(day: 1, second: -1)
return Calendar.current.date(byAdding: components, to: todayStart)!
}()
events = realm.objects(Event.self).filter("date BETWEEN %@", [todayStart, todayEnd])
Filter by day from NSDate in Realm, Swift
So, I find easy way:
Create public extension for String and create function with separate NSDate:
public static func sepaDate(whatNeed: String) -> String {
var currentDate = NSDate()
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = calendar!.components([.Day, .Month, .Year, .Minute, .Hour], fromDate: currentDate)
var forReturn: String = "0"
switch whatNeed {
case "day":
let valu = String(dateComponents.day)
forReturn = valu
case "month":
let valu = String(dateComponents.month)
forReturn = valu
case "year":
let valu = String(dateComponents.year)
forReturn = valu
case "hour":
let valu = String(dateComponents.hour)
forReturn = valu
case "minute":
let valu = String(dateComponents.minute)
forReturn = valu
default: print("Error")
}
return forReturn
}
}In Realm class, create separate date:
dynamic var minute = String.sepaDate("minute")
dynamic var hour = String.sepaDate("hour")
dynamic var day = String.sepaDate("day")
dynamic var month = String.sepaDate("month")
dynamic var year = String.sepaDate("year")In ViewController call to predicate
let dayday = String(dateComponents.day)
let monthmonth = String(dateComponents.month)
let yearyear = String(dateComponents.year)
let predicate = NSPredicate(format: "day = %@ AND month = %@ AND year = %@", dayday, monthmonth, yearyear)
generalRecords = uiRealm.objects(GeneralList).filter(predicate)
I hope it's help somebody...
Swift Realm add days to date in filter
I would suggest just storing the actual date you want to query against.
You know the last_record_date and the frequency_days so why not add them together and store that as a date.
For example;
Suppose the last_record_date is 2022-04-01 and frequency_days is 10 (days).
If you add the number of days onto last_record_date, the resultant date is 2022-04-10 (including the 1st).
So store that at a target_date property: 2022-04-10
Any time the either the frequency date or last_record_date changes you can simply calculate a new target date and store that.
I would suggest adding a function to you Realm class to do that for you, and if you need to store the frequency_days and last_record_date you can do that as well.
class Route: Object, ObjectKeyIdentifiable, Codable {
@Persisted(primaryKey: true) var id: Int?
@Persisted var frequency_days: Int?
@Persisted var last_record_date: Date?
@Persisted var target_date: Date?
func changeFrequencyDays(newDayCount: Int) {
self.frequency_days = newDayCount
//do some math to add newDayCount to the last_record_date
self.target_date = //new calculated date
}
func changeLastRecordDate(lastRecordDate: Date) {
self.last_record_date = lastRecordDate
//do some math to add frequency_days to the new lastRecordDate
self.target_date = //new calculated date
}
}
With the above, any time a frequency_days need to be updated or the last_record_date changes, call the appropriate function and that property will be updated along with updating the target_date property.
Unable to filter after Date in Realm swift
You should use:
.filter("\(key) <= %@", newDate as NSDate)
This is calling the overload of Realm's filter
method that accepts a format and arguments.
String(format:)
is not the right thing to use here, as that just does general string formatting. But here, you want the date to be formatted according to the rules of NSPredicate
formats. On the other hand, the key
can just be interpolated into the string because the name of the table column doesn't need a special format.
If key
comes from a UITextField
or something like that, then you might need to beware of injection attacks as well, and validate and/or escape the key
properly beforehand.
Filtering by days in the week without time (Realm & Swift)
Try this :
let realmObj = Realm()
let predicate = NSPredicate(format: "Start >= %@ AND End <= %@", start,end)
let results = realmObj.objects(Event.self).filter(predicate)
Filter array of all events and find which event is still going on
You will need to convert them into dates, using DateFormatter, and then use a .filter over the array and have it match on if the current date is in range.
If you have the ability to change the Event class, you can greatly simplify your code if you replace your Event class with the DateInterval class, which does the same thing:
let minutes = 60;
let formatter = DateFormatter()
formatter.dateFormat = "MM-dd-yyyy"
let event1 = DateInterval(
start: formatter.date(from: "12-12-2016")!,
duration: TimeInterval(20 * minutes)
)
let now = Date()
if (event1.contains(now)) {
print("Event 1 is still active")
}
How to set Local Notification for input date on Realm
I do not believe this is directly possible with Realm, alone. However you can just schedule the notification based off the date entered into the database.
https://developer.apple.com/documentation/usernotifications/scheduling_a_notification_locally_from_your_app
Just use:
// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.calendar = Calendar.current
dateComponents.weekday = 3 // Tuesday
dateComponents.hour = 14 // 14:00 hours
// Create the trigger as a repeating event.
let trigger = UNCalendarNotificationTrigger(
dateMatching: dateComponents, repeats: true)
Realm subquery sorted by Date
It's a shame that date
isn't an NSDate
property since you could easily just sort by descending order, and then use LinkingObjects
to look up the Event
in which that Date
object belongs:
class Event : Object {
dynamic var description = ""
let dates = List<Date>()
}
class Date : Object {
dynamic var date = NSDate()
let events = LinkingObjects(fromType: Event.self, property: "dates")
}
let realm = try! Realm()
let latestDate = realm.objects(Date.self).sorted("date", ascending: false).first
let latestEvent = latestDate.events.first
Unfortunately, as date
is a string, that might not work. You could try and used sorted()
on date
, but it will be sorting alphabetically, and not chronologically, so you may not get the latest date.
If that's the case, you'll need to manually implement a loop through each Date
object, parse it and perform the sorting yourself.
Related Topics
Why Do Some Types (E.G. Float80) Have a Memory Alignment Bigger Than Word Size
Error Using Associated Types and Generics
How to Find the Index of an Item in Swift
Truncatingremainder VS Remainder in Swift
Need Self to Set All Constants of a Swift Class in Init
iOS 9 iPad Keyboard Get Rid of "Undo View"
Ios9: Using Dynamic Framework with Simulator and Device
Arkit - How to Put 3D Object on Qrcode
Swiftui MACos Xcode Style Toolbar
Detect Ethernet/Wifi Network Change
Enumerateobjectsusingblock in Swift
"Nsurl" Is Not Implicitly Convertible to "Url"; Did You Mean to Use "As" to Explicitly Convert