Swift full date with milliseconds

Swift 5 to/from Timestamp String Extension

extension String {
    static func timestamp() -> String {
        let dateFMT = DateFormatter()
        dateFMT.locale = Locale(identifier: "en_US_POSIX")
        dateFMT.dateFormat = "yyyyMMdd'T'HHmmss.SSSS"
        let now = Date()

        return String(format: "%@", dateFMT.string(from: now))
    }

    func tad2Date() -> Date? {
        let dateFMT = DateFormatter()
        dateFMT.locale = Locale(identifier: "en_US_POSIX")
        dateFMT.dateFormat = "yyyyMMdd'T'HHmmss.SSSS"

        return dateFMT.date(from: self)
    }
}

Updated for Swift 3

let d = Date()
let df = DateFormatter()
df.dateFormat = "y-MM-dd H:mm:ss.SSSS"

df.string(from: d) // -> "2016-11-17 17:51:15.1720"

When you have a Date d, you can get the formatted string using a NSDateFormatter. You can also use a formatter to turn a string date based on your format into a Date

See this chart for more on what dateFormat can do http://waracle.net/iphone-nsdateformatter-date-formatting-table/

Tags:

Ios

Swift