Swift full date with milliseconds

IosSwift

Ios Problem Overview


Is any way to print full date with milliseconds?

For example, I'm doing this:

print("\(NSDate())")

But I'm just get this:

2016-05-09 22:07:19 +0000

How can I get the milliseconds too in the full date?

Ios Solutions


Solution 1 - Ios

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/

Solution 2 - Ios

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)
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpableirosView Question on Stackoverflow
Solution 1 - IosWillView Answer on Stackoverflow
Solution 2 - IosslashlosView Answer on Stackoverflow