find the current date and time in swift

You can find the current date and time in Swift using the Date class and the DateFormatter class. Here's an example:

main.swift
let now = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = formatter.string(from: now)
print("Current date and time: \(dateString)")
223 chars
7 lines

In this example, we first create a Date object representing the current date and time using the Date() initializer. Then, we create a DateFormatter object, set its time zone to the current time zone (you can change this if needed), and set its date format to "yyyy-MM-dd HH:mm:ss" (which will output the date and time in the format "YYYY-MM-DD HH:MM:SS").

Finally, we use the formatter.string(from: now) method to convert the Date object to a string in the desired format, and print it out.

gistlibby LogSnag