0

I want to set DatePicker from a String to a certain date when it appears.

@State var staff: Staff
DatePicker(selection: $staff.birthDate, in: ...Date(),displayedComponents: .date) {
            Text("Birth Date:")
        }

What I expect is something like that, but it didn't work because selection requires Binding<Date> and $staff.birthDate is a String. How do I convert it?

I tried to create a func to format it like so:

func formatStringToDate(date: String?) -> Binding<Date> {
     @Binding var bindingDate: Date
     let dateForm = DateFormatter()
     dateForm.dateFormat = "dd-MM-YYYY"
//    _bindingDate = date
     return dateForm.date(from: date ?? "")
}

But it still doesn't work. Any idea on how to solve this? Or did I approach this wrong?

Thankyou in advance.

1 Answer 1

2

You need to use another date parameter for birth date. So your Staff class is

class Staff: ObservableObject {
    @Published var birthDate: String = "02-05-2021"
    @Published var date: Date = Date()
    
    init() {
        self.date = DateFormatter.formate.date(from: birthDate) ?? Date()
    }
}

Now create one date formattter in the DateFormatter extension.

extension DateFormatter {
    static var formate: DateFormatter {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd-MM-yyyy"
        return dateFormatter
    }
}

Now, in view struct use the .onChange method. It will execute each time when the date is changed and you need to convert this date to a string and store it in your birthDate string var.

struct ContentView: View {
    
    @StateObject var staff: Staff = Staff()
  
    var body: some View {
        DatePicker(selection: $staff.date, in: ...Date(),displayedComponents: .date) {
            Text("Birth Date:")
        }
        .onChange(of: staff.date) { (date) in
            staff.birthDate = DateFormatter.formate.string(from: date)
        }
    }
}

If your project target is from iOS 13 then you can use custom binding.

struct ContentView: View {
    
    @StateObject var staff: Staff = Staff()
  
    var body: some View {
        DatePicker(selection: Binding(get: {staff.date},
                                      set: {
            staff.date = $0;
            staff.birthDate = DateFormatter.formate.string(from: $0)
        }), in: ...Date(),displayedComponents: .date) {
            Text("Birth Date:")
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.