To convert a Date
to a String
with a given format you can use a DateFormatter
:
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
let date = "\(Date(), formatter: dateFormatter)"
This will print the current date in the d/m/yy format.
If you also want to include the time of the date you need to specify the timeStyle
:
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
let date = "\(Date(), formatter: dateFormatter)"
Finally, if you want to fix a format representation and customise it to your needs you can specify the dateFormat
instead:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm YYYY"
let date = "\(Date(), formatter: dateFormatter)"