TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Sort by Date but not Time

Forums > SwiftUI

I think this has to be a simple fix, but I can't find it.

I want to sort information by date and by type. But the type sort isn't working. I move elements from type to type and they stay in the same order. I think this is because the time element of the date is keeping them in the same order because when I move the dates, they resort. But if they're all on the same date, they remain in the same order no matter what type I give them.

Is there a way to write a Sort array and tell it to ignore the time component of the timestamp the way you can omit time when formatting how a date is displayed?

MODEL

@Model
class Meal: Identifiable {
    let id = UUID()
    var title: String = ""
    var type: String = ""
    var date: Date = Date()

    init(title: String, type: String, date: Date) {
        self.title = title
        self.type = type
        self.date = date
    }
}

SORT

@Query(sort: [SortDescriptor(\Meal.date), SortDescriptor(\Meal.type)]) private var meals: [Meal]

DISPLAY

            HStack{
                    Label(meal.title, systemImage: "cup.and.saucer")
                Spacer()
                HStack{
                    Text(meal.date.formatted( Date.FormatStyle()
                        .weekday(.abbreviated)
                    ))
                    Text(meal.date.formatted( Date.FormatStyle()
                        .day(.twoDigits)
                        .month(.abbreviated)
                    ))
                }
            }

   

Do you need the Time? If no then add this to your project

extension Date {
    var startOfDay: Date {
        Calendar.current.startOfDay(for: self)
    }
}

then in your class do

var date = Date.now.startOfDay

However if you require the time not to be 00:00 (startOfDay) however would like to ignore it in sort then do it

@Query(sort: [SortDescriptor(\Meal.date.startOfDay), SortDescriptor(\Meal.type)]) private var meals: [Meal]

See if that will do the trick!

   

I don't need time at all. Thanks!

   

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.