Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

前端 未结 19 2046
时光说笑
时光说笑 2020-11-22 02:16

I am trying to get the difference between the current date as NSDate() and a date from a PHP time(); call for example: NSDate(timeIntervalSin

19条回答
  •  广开言路
    2020-11-22 02:59

    In Swift 2.2

        /// Returns the amount of years from another date
    func years(fromdate: NSDate) -> Int {
        return NSCalendar.currentCalendar().components([.Year], fromDate: fromdate, toDate: NSDate(), options: []).year ?? 0
    }
    /// Returns the amount of months from another date
    func months(fromdate: NSDate) -> Int {
        return NSCalendar.currentCalendar().components([.Month], fromDate: fromdate, toDate: NSDate(), options: []).month ?? 0
    }
    /// Returns the amount of weeks from another date
    func weeks(fromdate: NSDate) -> Int {
        return NSCalendar.currentCalendar().components([.WeekOfYear], fromDate: fromdate, toDate: NSDate(), options: []).weekOfYear ?? 0
    }
    /// Returns the amount of days from another date
    func days(fromdate: NSDate) -> Int {
        return NSCalendar.currentCalendar().components([.Day], fromDate: fromdate, toDate: NSDate(), options: []).day ?? 0
    }
    /// Returns the amount of hours from another date
    func hours(fromdate: NSDate) -> Int {
        return NSCalendar.currentCalendar().components([.Hour], fromDate: fromdate, toDate: NSDate(), options: []).hour ?? 0
    }
    /// Returns the amount of minutes from another date
    func minutes(fromdate: NSDate) -> Int {
        return NSCalendar.currentCalendar().components([.Minute], fromDate: fromdate, toDate: NSDate(), options: []).minute ?? 0
    }
    /// Returns the amount of seconds from another date
    func seconds(fromdate: NSDate) -> Int {
        return NSCalendar.currentCalendar().components(.Second, fromDate: fromdate, toDate: NSDate(), options: []).second ?? 0
    }
    

提交回复
热议问题