Search code examples
swift

Swift Date() vs Date.now - When to use which?


What's the difference? Both return a Date-object.

When should one use which?

let dateConstructor = Date()
let dateProp = Date.now

print(dateConstructor) // 2024-07-15 14:10:58 +0000
print(dateProp)        // 2024-07-15 14:10:58 +0000

Solution

  • There is no "should".

    Date.now is a later addition to the language (it was introduced in iOS 15, I believe), and has the advantage, for humans, that you are thus saying what you mean (rather than relying on the "surprise" that Date() happens to mean the date-time at the moment of instantiation). It was introduced for that exact reason; it simply fills a hole in the language — and indeed, most of us were already defining Date.now in an extension to fill that hole, and Apple simply made that official.

    Thus I recommend using Date.now if you don't have to support an earlier version of iOS. But they are complete synonyms all the same. I doubt that Date() would ever be deprecated, so they will presumably continue side by side.