Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change selected date format from DatePicker SwiftUI

Is there a way to format the date?(from the position indicated by the arrow in the picture) I know it is formatted based on the locale but is there a way to format it myself?

enter image description here

struct ContentView: View {

    @State private var selectedDate = Date()

    var body: some View {
        Form {

            DatePicker(selection: $selectedDate, in: ...Date(), displayedComponents: .date) {
                Text("From*")
            }
        }
    }
}
like image 671
Claudiu Avatar asked Nov 26 '19 13:11

Claudiu


1 Answers

The only way I could figure to accomplish this is to create my own custom DatePicker view and use onAppear on the TextField to update an @State selectedDateText: String variable for displaying in the TextField. This feels like a hack and I’m almost embarrassed to post it but it works. I’m new at Swift and iOS programming in general so I’m sure someone will come along with a better answer so I’ll offer this for what it’s worth. My custom view is something like this:

struct CustomDatePicker: View {
  @Binding var date: Date

  @State private var showPicker: Bool = false
  @State private var selectedDateText: String = "Date"

  private var selectedDate: Binding<Date> {
    Binding<Date>(get: { self.date}, set : {
        self.date = $0
        self.setDateString()
    })
  } // This private var I found… somewhere. I wish I could remember where

  // To take the selected date and store it as a string for the text field
  private func setDateString() {
    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM dd, yyyy"

    self.selectedDateText = formatter.string(from: self.date)
  }

  var body: some View {
    VStack {
        HStack {
            Text("Date:")
                .frame(alignment: .leading)
            
            TextField("", text: $selectedDateText)
                .onAppear() {
                    self.setDateString()
                }
                .disabled(true)
                .onTapGesture {
                    self.showPicker.toggle()
                }
            .multilineTextAlignment(.trailing)
        }            
        
        if showPicker {
            DatePicker("", selection: selectedDate,
            displayedComponents: .date)
            .datePickerStyle(WheelDatePickerStyle())
            .labelsHidden()
        }
    }
  }
}

EDIT: I figured out where I got the private var code. It was from this post: How to detect a value change of a Datepicker using SwiftUI and Combine?

like image 97
Chris Avatar answered Oct 24 '22 04:10

Chris