How to add characters into dateFormatter

Solutions Collect From Internet About “How to add characters into dateFormatter”

Add single quotes

xFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-04:00"

From the documentation:

… This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.

Source: Date Format Patterns


Be aware that the time zone is just an amendment to the string, it’s not considered by the date formatter.

To consider the time zone you have to set the timeZone of the formatter

xFormatter.timeZone = TimeZone(secondsFromGMT: -14400)

In iOS 10.0+ and macOS 10.12+ there is a more convenient way to create an ISO8601 string

let isoFormatter = ISO8601DateFormatter()
isoFormatter.timeZone = TimeZone(secondsFromGMT: -14400)
isoFormatter.formatOptions = .withInternetDateTime
print(isoFormatter.string(from: Date()))