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

Date in Fetch Request Predicate

Forums > SwiftUI

Hey there!

So basically, I'm trying to check if a date from fetch request in with the start and end of today which I get from <<Date()>> in swiftUI, but how do I do that.

I am so far unable to even store the begining of today as a date type in a constant or variable. When/if I accomplish that, how would I go about seeing if the fetched date is in between the start and end of today values?

I hope that makes sense, if you don't understand what I am asking, please ask me because I have been stuck on this problem for a long time and can't find a solution.

Thank you, RoroCoder

2      

Here are some starting points, to consider, for your question.

You can access the date methods of Calendar

if Calendar.current.isDateInToday(<your date>) {   // <your date> is from the FetchResult
   // some code here
}

If you need to create your own date, you will need to use the .byAdding & .to method of Calendar.current.date()

Alternatively you could also manipulate the date components directly. Here is a date function I wrote for myself.

/// Returns the fixed date and time 12:00:00 on the specified date
func middayOnDate (on date: Date) -> Date {
    var components = DateComponents()
    components.hour = 12
    components.minute = 0
    components.second = 0
    components.day = Calendar.current.component(.day, from: date)
    components.month = Calendar.current.component(.month, from: date)
    components.year = Calendar.current.component(.year, from: date)

    return (Calendar.current.date(from: components)!)
}

Hope this helps you.

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.