UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Filter on Date

Forums > Swift

I have a CoreData entity that has an attribute called dateLastUsed and I store a Date() in it and anytime this hymn is sung I update that date to the Date() its being used.

I am trying to figure out filter on that. My view has a segmented control with items for 30,60,90 days and 6 months and 1 year. I need help figuring out how to use @FetchRequest with a predicate to say give me all the hymns that have been sung in the last 30,60,90 days etc also 6 month and 1 year.

This is what I wrote but i'm not sure if this is correct.

@FetchRequest(entity: HymnData.entity(), sortDescriptors: [
        NSSortDescriptor(keyPath: \HymnData.hymnName, ascending: true)
        ],
        predicate: NSPredicate(format: "dateLastUsed < %@", 30)
    ) private var hymnData: FetchedResults<HymnData>

Any help here would be great

Mark

2      

Date is stored as a number of seconds since particular point in time in Core Data so you cannot create NSPredicate and compare based on days.

I would use Calendar.current to get a Date that is 30 days ago and use that with the NSPredicate to get records sung in the last 30 days.

You can use Calendar to add days to Date instance, to subtract days, you can add negative number. So -30 in this case.

2      

Thank you this worked. Thanks for explanation on how the date is stored.

Mark

3      

Is there a way to see if a date entered into core data is equal to todays date (exlcuding hours, minutes seconds ...) with predicate during Fetch Request.

Whenever I search online, it shows me how you would've done it with swift 2 or 3 but that code doesn't work with Swift 5. I am a beginner and I simply want to know how core data and fetch requests work. Also, is there a place that explains how dates in swift work cos they are so confusing and complicated.

Thanks, Rohan

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.