Filter by Day from Nsdate in Realm, Swift

Filter by day from NSDate in Realm, Swift

So, I find easy way:

  1. 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
    }
    }
  2. 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")
  3. 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...

How to filter Realm objects via an NSDate property

The immediate problem is that you're using Swift's string interpolation to build your predicate rather than using NSPredicate's argument substitution. This results in your predicate being something like:

createdAt <= '2015-03-19 07:00:00 +0000'

This is attempting to compare createdAt, a date, with a string literal. Using NSPredicate's argument substitution would look like:

let list = RealmDB.objects(TaskList).filter("createdAt <= %@", datex)

Note that the way you're computing the date isn't correct in the face of leap days, leap seconds, discontinuities due to daylight savings, and so forth. You should use NSCalendar's methods for date math rather than doing math with magic constants:

let calendar = NSCalender.currentCalendar()
let datex = calendar.dateByAddingUnit(.Year, value: -1, toDate: calendar.startOfDayForDate(NSDate()), options: [.MatchFirst])

Keep in mind that an NSDate represents a single point in time, independent of any time zone. The default formatting of NSDate, used when -[NSDate description] is called, happens to format the date in UTC. If you'd like to format the date to a string using a different time zone, you can use NSDateFormatter and set the time zone explicitly.

Filter by date component in Realm

Unfortunately it's not that simple. Results.filter takes nspredicate or a predicate format string.

let trainingsBetweenDates = realm.objects(Trainings.self).filter("date BETWEEN {%@, %@}", startDate, endDate)

you can make the boundary dates yourself using the methods described here:How do you create a swift Date object

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])

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)

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.

NSPredicate: filtering objects by day of NSDate property

Given a NSDate * startDate and endDate and a NSManagedObjectContext * moc:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", startDate, endDate];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:moc]];
[request setPredicate:predicate];

NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];


Related Topics



Leave a reply



Submit