NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

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

   

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.

   

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

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

Reply to this topic…

You need to create an account or log in to reply.

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.