Search code examples
swiftdatetimensdatedate-formatting

Swift Print full date with milliseconds


Is there 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?


Solution

  • Updated for Swift 3

    let date = Date()
    let formatter = DateFormatter()
    formatter.dateFormat = "y-MM-dd H:mm:ss.SSSS"
    
    formatter.string(from: date) // -> "2016-11-17 17:51:15.1720"
    

    When you have a Date date, you can get the formatted string using a DateFormatter. 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/