Swift Print full date with milliseconds
Asked Answered
D

3

71

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?

Decorum answered 9/5, 2016 at 22:11 Comment(3)
You need to use NSDateFormatter with the proper dateFormat. Printing the actual date object gives you the string representation for the date in UTC, not necessarily the time zone you are interested in.Chilly
You can use NSDate().timeIntervalSince1970 to get millisecondsShebeen
@YuriRomanchenko timeIntervalSince1970 returns seconds not milliseconds.Teredo
R
156

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/

Reticulate answered 9/5, 2016 at 22:35 Comment(7)
That's a very misleading format since you make the fractional seconds look like a timezone. A much better format would be to have ss.SSS at the end instead of ss +SSSS.Haulm
You also have the wrong format for the year. Use yyyy, not Y.Haulm
I agree about the seconds using the ss.SSSS format but it looked like that's what they were asking for? I'll edit my answer in case someone comes across this and just copy pastes. As per the year comment, Y returns the ISO 8601 spec year.Reticulate
Read the docs for y and Y. They are two different years. 99.99% of the time a person wants y, not Y. And what makes you think the OP wants the milliseconds formatted like a timezone? They are simply showing the standard output of printing a date (which shows the timezone offset by default) and asks how to add milliseconds to that output. That doesn't mean they want the milliseconds formatted like a timezone.Haulm
Y is wrong. it will return the year of a week-based calendar. A subtle error that even apple got wrong before.Sarinasarine
I created a snippet that proves Y is wrong: gitlab.com/snippets/19107 It just creates a date from a string and than creates a string form the date — and the year is off by 1. if you change the Y from the format to y the result is correct.Sarinasarine
Wouldn't it be y-MM-dd H:mm:ss.SSS (only 3 S) for milliseconds?Scintillation
C
7

Swift 5 to/from Timestamp String Extension

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

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

    func tad2Date() -> Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "en_US_POSIX")
        dateFormatter.dateFormat = "yyyyMMdd'T'HHmmss.SSSS"
    
        return dateFormatter.date(from: self)
    }
}
Cornela answered 26/3, 2020 at 12:23 Comment(0)
D
0

Swift 5

iOS 15.0+ / macOS 12.0+

You can now also use the locale-aware formatted() API to display milliseconds using the .secondFraction(.fractional(3)) modifier:

let date = Date()
print(date.formatted(Date.FormatStyle().month(.twoDigits).day(.twoDigits).year().hour().minute().second(.twoDigits).secondFraction(.fractional(3)).timeZone(.iso8601(.short))))
// "18.04.2024, 11:50:14,696 +0200" (my current locale is "DE")

Now that's some long string. You can break it down and store your format somewhere for re-use:

let preferredFormat = Date.FormatStyle()
    .weekday(.abbreviated)
    .month(.twoDigits)
    .day(.twoDigits)
    .year()
    .hour()
    .minute()
    .second(.twoDigits)
    .secondFraction(.fractional(3))
    .timeZone(.iso8601(.short))
    .locale(.init(identifier: "US"))

print(date.formatted(preferredFormat))
// "Thu, 04/18/2024, 11:49:44.133 +0200"
Dialect answered 18/4 at 9:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.