How to display only "day and month" from Date-input in SwiftUI

1.6k Views Asked by At

I have a form where the user should pick a date, and write a sum. It works fine, but when i display the information (form core data) in a List the whole date string is shown (time zone, time, year etc). There must be an easy way to get just the month and day+date displayed? like "Thursday, January 28".

My code for ContentView:

struct ContentView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Kostnad.entity(), sortDescriptors: []) var kostnader:
    FetchedResults<Kostnad>
    
    @State private var showingAddScreen = false
    
 
    
    
    var body: some View {
        NavigationView{
           // Text("Count: \(kostnader.count)")
            List{
                ForEach(kostnader, id: \.self) { kostnad in
                    VStack{
                        Text("\(kostnad.sum)")
                        Text("\(kostnad.dato ?? Date())")
                    }
                }
                .onDelete(perform: deleteBooks)
               // Text("Month: \(components)")
            }
            .navigationBarTitle("Legg til")
            .navigationBarItems(leading: EditButton(), trailing:
                Button(action: {
                    self.showingAddScreen.toggle()
                }) {
                    Image(systemName: "plus")
                }
            )
            .sheet(isPresented: $showingAddScreen) {
                AddKostnad().environment(\.managedObjectContext, self.moc)
            }
        }
    }
    func deleteBooks(at offsets: IndexSet) {
        for offset in offsets {
            let kostnad = kostnader[offset]
            moc.delete(kostnad)
        }
        
        try? moc.save()
    }
}

Image of the output the way it is now!

1

There are 1 best solutions below

0
On

Use DateFormatter extension.

extension DateFormatter {
    static let displayDate: DateFormatter = {
         let formatter = DateFormatter()
         formatter.dateFormat = "EEEE, MMMM dd"
         return formatter
    }()
}

and inside the view

Text(DateFormatter.displayDate.string(from: kostnad.dato ?? Date()))