Home > Blockchain >  How to set the time to a standard value when using a DatePicker in SwiftUI
How to set the time to a standard value when using a DatePicker in SwiftUI

Time:10-16

I have a date-picker in my app, which only selects the date, not the time. Looks like this:

DatePicker("Birthday",
          selection: $date,
          displayedComponents: [.date])

A date picker gives you a date object to work with. So, when the user selects a date, it of course also comes with a time, timezone, etc. My problem is, that the time is set to the current time by default. However, I need it to be set to midnight always. How can I provide a default value?

A possible solution that came to my mind was using a formatter and storing the date as a String (instead of a Date), but since I need to do some work with it later (e.g. calculate days between two dates), this doesn't seem like the best approach to me.

CodePudding user response:

you could try this:

struct ContentView: View {
    @State var date = Date()
    
    var body: some View {
        VStack {
            Text("\(date)")
            DatePicker("Birthday", selection: $date, displayedComponents: [.date])
                .onChange(of: date) { newDate in
                    if let midnight = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: newDate) {
                        date = midnight
                        
                    }
                }
        }
    }
}

or this:

struct ContentView: View {
    @State var date = Date()
    
    var body: some View {
        VStack {
            Text("\(date)")
            DatePicker("Birthday", selection: $date, displayedComponents: [.date])
        }
        .onAppear {
            if let midnight = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date()) {
                date = midnight
            }
        }
    }
}

or this:

struct ContentView: View {
    @State var date = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!
    
    var body: some View {
        VStack {
            Text("\(date)")
            DatePicker("Birthday", selection: $date, displayedComponents: [.date])
        }
    }
}
  • Related