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

末鹿安然 提交于 2019-12-11 04:35:20

问题


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)

回答1:


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.



来源:https://stackoverflow.com/questions/41198803/how-to-convert-from-nsdatetimeintervalsince1970-to-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!