- In Swift, normally variable names are lowercased:
let dates : [String] = ["2021-01-07","2021-01-19"]
- To display these as-written in
Text
, you need to turn [String]
into String
. One possibility is:
Text(dates.joined(separator: ", "))
- If you want them in a different format, you need to convert from
String
to Date
:
struct ContentView: View {
@State private var formatterIn = DateFormatter()
@State private var formatterOut = ISO8601DateFormatter()
let dates : [String] = ["2021-01-07","2021-01-19"]
var datesToNewFormat : String {
formatterIn.dateFormat = "yyyy-MM-dd"
return dates.compactMap { formatterIn.date(from: $0) }.map { formatterOut.string(from: $0)}
.joined(separator: ", ")
}
var body: some View {
VStack {
Text(dates.joined(separator: ", "))
Text(datesToNewFormat)
}
}
}
Note on this last item that it deals with timezone conversion as well. In your example, if you want T00:00:00Z
, the easiest thing would be to just append that onto the end of your original strings:
dates.map { $0 + "T00:00:00Z" }
Or, you could use DateComponents to manually set the hour to zero. This all probably depends on where your input is coming from and what your intent is with the output.
It is also probably worth mentioning that SwiftUI has some built-in tools for displaying Date
in Text
. See https://www.hackingwithswift.com/quick-start/swiftui/how-to-format-dates-inside-text-views