Search code examples
iosswiftstringswiftuidatepicker

Convert Date to String in IOS Swiftui


Date Picker :

DatePicker(selection: $vm.user.movingdate,
           displayedComponents: [.date]) {
    Label("Select a date", systemImage: "calendar")
}

when i print the selected date , i got

2023-05-19 18:32:00 +0000

how to convert it to String and i need only 2023-05-19

Expected Output is "2023-05-19"


Solution

  • I reopened the question which was marked as duplicate because both linked answers don't cover the SwiftUI-way to format the date

    let date = Date()
    let formattedDate = date.formatted(.iso8601.year().month().day())