2

Can I create a DatePicker that displays a specific date?

Here is my code:

struct OnlineShop: View {
  @State private var date = Date()
  var body: some View {
    DatePicker(
      "Start Date",
      selection: $date,
      displayedComponents: [.date]
    )}
}

This code displays the current date on the picker. I want to show a specific date, such as 8/29/1987.

How can I do this?

2 Answers 2

1

Sure, just create your own date and set it.

struct OnlineShop: View {
    @State private var date = Date()
    
    var body: some View {
        Text("Hello, Online!")
        
        DatePicker(
            "Start Date",
            selection: $date,
            displayedComponents: [.date]
        )
        .onAppear {
            let calendar = Calendar(identifier: .gregorian)
            let components = DateComponents(year: 1987, month: 8, day: 29)
            if let customDate = calendar.date(from: components) {
                self.date = customDate /// set customDate to date
            }
        }
    }
}

Result:

Date picker shows "Aug 29, 1987"

Sign up to request clarification or add additional context in comments.

Comments

1

This is possible. You can specify any component(s), like the year, month, day, hour, etc. using the DateComponents initializer with Calendar.current.

You need to initialize your date variable like so:

@State private var date: Date = Calendar.current.date(from: DateComponents(year: 1987, month: 8, day: 27)

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.