Search code examples
iosswiftcore-dataswiftuipredicate

Show only the last 24hr/today inputted data from swiftui coredata


Im trying to show the list of the only today or last 24 hr inputted data from swiftui coredata. I didn't know the syntax or logic how to get the today data on the predicate of @FetchRequest. Can someone help, here is the code to show all the data

@FetchRequest(
    entity: ExpenseLog.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \ExpenseLog.date, ascending: true)
    ]
    //,predicate: NSPredicate...
)
private var result: FetchedResults<ExpenseLog>

...

                                ForEach(self.result)
                                {
                                    (log: ExpenseLog) in


                                    ZStack{
                                    HStack(spacing: 16) {
                                                           CategoryImageView(category: log.categoryEnum)
                                                           VStack(alignment: .leading, spacing: 8) {
                                                               Text(log.nameText).font(.headline)
                                                               Text(log.dateText).font(.subheadline)
                                                           }
                                                           Spacer()
                                                           Text(log.amountText).font(.headline)

                                    } .padding(.vertical, 8) .padding(.horizontal,4)
                                      }

                                }

Solution

  • just filter your list with

    Calendar.current.isDateInToday(yourDate)
    Calendar.current.isDateInYesterday(yourDate)