var currentDT = Date()
print(currentDT)
This prints more information than I need right now. How can I just take time (hh:mm:ss) or date (dd-mm-yy) from this? This feels like a stupid question. But I couldn't manage to find any good documentation on this.
Actually this is pretty easy this days
Text("the time is \(Date().formatted(.dateTime.hour().minute().second()))!")
You are printing the Date object directly, which uses a predetermined description algorithm to display the date.
But one should not try to parse strings out of that. Instead use DateFormatter to build your date/time strings. So, you might have a date formatter for the date and another for the time:
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .short
return formatter
}()
let timeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.timeStyle = .medium
return formatter
}()
Note, I would advise not using hard-coded date format strings and setting the formatter’s dateFormat string, but rather use these “style” properties to dictate the type of string you want, while still honoring the preferences of the user (e.g. 01-02-21 will be interpreted as January 2nd in the US, but February 1st in many other locales).
Anyway, now that you have those formatter properties, you can use them in your code. E.g., given that you tagged this as swiftui, you might use Text with formatter:
var body: some View {
VStack {
Text("Date: \(date, formatter: dateFormatter)")
Text("Time: \(date, formatter: timeFormatter)")
}
}
Or, you can use the DateFormatter method string(from:) to manually get the string:
let string = dateFormatter.string(from: date)
print(string) // 5/30/21 in the US; 30/5/21 in many other locales
On the other hand, if this string was not for display in the UI and you really wanted a fixed string format (e.g. you were writing the date string to persistent storage or including it in some web request), you would instead use ISO8601DateFormatter (which produces ISO8601/RFC3339 date strings, which are fixed format and, by default, in GMT/Zulu), e.g.:
let formatter = ISO8601DateFormatter()
let string = formatter.string(from: date)
print(string) // 2021-05-30T17:27:45Z
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With