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

You can use DateFormatter class to format a Date object to a string representation with a specific format.

main.swift
let date = Date() // current date

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // set the format string
let formattedDate = dateFormatter.string(from: date) // convert Date to String
print(formattedDate) // prints something like "2021-09-24 14:32:10"
292 chars
7 lines

In the code above:

  • We create a Date object representing the current date and time.
  • We instantiate a DateFormatter object and set its dateFormat property to the desired format string. yyyy represents the year with four digits, MM represents the month with two digits, dd represents the day with two digits, HH represents the hour in 24-hour format with two digits, mm represents the minute with two digits, and ss represents the second with two digits.
  • We call the string(from:) method of the DateFormatter object to obtain the string representation of the Date object using the specified format.
  • Finally, we print the formatted date string.

gistlibby LogSnag