Search code examples
swiftnsdate

How to get the number of days since NSDate's Reference Date?


I saw in the Apple's documentation about NSDate that Date objects represents an invariant time interval relative to an absolute reference date. How can I get the number of days since that Reference Date?

Edit: I saw solutions for a similar question, but I'm searching for a solution that don't force me to enter specific dates.


Solution

  • You can use calendar method dateComponents from Date to Date and pass only the day component:

    let date = Date(timeIntervalSinceReferenceDate: 0)     //  "2001-01-01 00:00:00 +0000" 
    let days = Calendar.current.dateComponents([.day], from: date, to: Date()).day    // 5971