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

You can use the DateFormatter class in Swift to format a date object into a string in the desired format. Here's an example code snippet:

main.swift
let date = Date()

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"

let dateString = formatter.string(from: date)
print(dateString) // Output: "2022-01-04 15:20:30.123"
202 chars
8 lines

In the dateFormat property of the DateFormatter instance, you can specify the format of the date string using various placeholders. For example, yyyy represents the year, MM represents the month, dd represents the day, HH represents the hour in 24-hour time format, mm represents the minute, ss represents the second, and SSS represents the millisecond.

Next, you can use the string(from:) method of the DateFormatter instance to convert the date object to a formatted string. Finally, you can use the formatted string in your code as desired.

gistlibby LogSnag