【问题标题】:How to convert from NSDate(timeIntervalSince1970 to NSDate()?如何从 NSDate(timeIntervalSince1970 转换为 NSDate()?
【发布时间】:2016-12-17 12:55:18
【问题描述】:

这是我的代码。但是一个错误说,不能使用类型参数列表调用 dateComponent...

 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 swift3 nsdate nscalendar


    【解决方案1】:

    在 Swift 3 中,NSCalendar.current 返回一个 Calendar,即 Foundation NSCalendar 类型的 Swift 值包装器类型。

    dateComponents() 接受一个 Set<Calendar.Component> 和两个 Date 参数。 DateNSDate 的 Swift 值包装类型。

    当现有的 Foundation API 被导入 Swift 时,类型会自动桥接,这就是为什么NSCalendar.current 返回 Calender 而不是 NSCalendar

    值类型在 Swift 3 中是首选的,因为它们 提供适当的值语义并改用letvar 不可变和可变的变体。

    把它们放在一起:

    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 值包装器类型的更多信息和 它们对应的 Foundation 类型,请参见 SE-0069 Mutability and Foundation Value Types, 或中的“桥接类型”部分 Working with Cocoa Frameworks 在“将 Swift 与 Cocoa 和 Objective-C 一起使用”中 参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 2011-11-25
      • 1970-01-01
      • 2010-12-19
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多