format a date in to the format 'yyyy-mm-dd hh:mm:ss' in swift in swift

You can use DateFormatter class to achieve this. Here's an example code:

main.swift
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let formattedDate = dateFormatter.string(from: date)
print(formattedDate) // prints "2022-05-04 15:30:45"
209 chars
6 lines

Here, we are creating an instance of Date using Date() constructor. Then, we are creating another instance of DateFormatter class and setting its dateFormat property to the desired format. Finally, we are using string(from: date) method of the dateFormatter instance to get the formatted date string.

gistlibby LogSnag