okami mac
okami mac

Reputation: 33

Create DatePicker with specific date in SwiftUI

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?

Upvotes: 2

Views: 1297

Answers (2)

Ben Myers
Ben Myers

Reputation: 1395

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)

Upvotes: 1

aheze
aheze

Reputation: 30228

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"

Upvotes: 1

Related Questions