Search code examples
swiftswift3nsdatenscalendar

How to convert from NSDate(timeIntervalSince1970 to NSDate()?


This is my code. But an error said, cannot invoke dateComponent with an argument list of type...

 let fromDate = NSDate(timeIntervalSince1970: TimeInterval(tweetsArray[indexPath.row].timestamp)!)

        let toDate = NSDate()

        let components : NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth]

        let differenceOfDate = NSCalendar.current.dateComponents(components, from: fromDate, to: toDate)

Solution

  • In Swift 3, NSCalendar.current returns a Calendar, which is the Swift value wrapper type for the Foundation NSCalendar type.

    dateComponents() takes a Set<Calendar.Component> and two Date arguments. Date is the Swift value wrapper type for NSDate.

    When existing Foundation APIs are imported into Swift, the types are bridged automatically, that why NSCalendar.current returns a Calender and not NSCalendar.

    The values types are preferred in Swift 3 because they provide proper value semantics and use let and var instead of immutable and mutable variants.

    Putting it all together:

    let fromDate = Date(timeIntervalSince1970: ...)
    let toDate = Date()
    let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
    let differenceOfDate = Calendar.current.dateComponents(components, from: fromDate, to: toDate)
    

    For more information about Swift 3 value wrapper types and their corresponding Foundation types, see SE-0069 Mutability and Foundation Value Types, or the section "Bridged Types" in Working with Cocoa Frameworks in the "Using Swift with Cocoa and Objective-C" reference.