convert date to iso8601 in swift

To convert a Date object to ISO8601 string format, you can use the ISO8601DateFormatter class in Swift. Here's an example code snippet:

main.swift
let date = Date()

let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions.insert(.withFractionalSeconds)

let isoString = dateFormatter.string(from: date)

print(isoString) // Output: "2022-02-15T14:30:00.000Z"
227 chars
9 lines

In this example, we first create a Date object representing the current date and time. We then create an instance of ISO8601DateFormatter, and set the formatter's formatOptions property to include fractional seconds. Finally, we use the formatter's string(from:) method to convert the date object to an ISO8601 string representation.

Note that the Z at the end of the output string represents the UTC time zone. If you want to use a different time zone, you can set the formatter's timeZone property to the desired value.

gistlibby LogSnag