如何从 NSDate(timeIntervalSince1970) 转换为 NSDate()? [英] How to convert from NSDate(timeIntervalSince1970 to NSDate()?
问题描述
这是我的代码.但是一个错误说,无法使用类型为参数列表调用 dateComponent...
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)
推荐答案
在 Swift 3 中,NSCalendar.current
返回一个 Calendar
,它是Foundation NSCalendar
类型的 Swift 值包装器类型.
In Swift 3, NSCalendar.current
returns a Calendar
, which is the
Swift value wrapper type for the Foundation NSCalendar
type.
dateComponents()
接受一个 Set
和两个 Date
参数.Date
是 NSDate
的 Swift 值包装器类型.
dateComponents()
takes a Set<Calendar.Component>
and two Date
arguments. Date
is the Swift value wrapper type for NSDate
.
当现有的 Foundation API 导入 Swift 时,类型会自动桥接,这就是为什么 NSCalendar.current
返回 Calender
而不是 NSCalendar
.
When existing Foundation APIs are imported into Swift, the types are bridged automatically, that why NSCalendar.current
returns a Calender
and not NSCalendar
.
值类型在 Swift 3 中是首选的,因为它们提供适当的值语义并使用 let
和 var
代替不可变和可变变体.
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.
综合起来:
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)
有关 Swift 3 值包装器类型的更多信息和它们对应的基础类型,见SE-0069 可变性和基础值类型,或桥接类型"部分参考.
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.
这篇关于如何从 NSDate(timeIntervalSince1970) 转换为 NSDate()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!