Skip to content

Instantly share code, notes, and snippets.

@anvarazizov
Created October 13, 2017 01:03
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save anvarazizov/2fab5aa77e687f2c35a27ce09d430d8e to your computer and use it in GitHub Desktop.
Save anvarazizov/2fab5aa77e687f2c35a27ce09d430d8e to your computer and use it in GitHub Desktop.
print time in swift with milliseconds
func printDate(string: String) {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss.SSSS"
print(string + formatter.string(from: date))
}
@lucaspisso
Copy link

e

@tcobbs-bentley
Copy link

This is super useful, but the format should be "HH:mm:ss.SSS" (three big S's). The fourth S puts a 0 at the end of all values.

@nkalvi
Copy link

nkalvi commented Feb 6, 2023

There are many convenient options now:

    let date = Date.now
    let formattedFractional = date.formatted(.dateTime.hour().minute().second().secondFraction(.fractional(3)))
    // example: "8:07:48.145 AM"
    print(formattedFractional)

Check out What's new in Foundation from #wwdc21

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment