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?

Ben Myers
  • 1,173
  • 1
  • 8
  • 25
okami mac
  • 23
  • 3

2 Answers2

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"

aheze
  • 24,434
  • 8
  • 68
  • 125
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)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ben Myers
  • 1,173
  • 1
  • 8
  • 25