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

前端 未结 19 2042
时光说笑
时光说笑 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:46

    Use this code:

    let registrationDateString = "2008-10-06 00:00:00"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
        if let registrationDate = dateFormatter.date(from: registrationDateString) {
            let currentDate = Date()
            let dateDifference = Calendar.current.dateComponents([.day, .month, .year],
                                                                   from: registrationDate,
                                                                   to: currentDate)
            print("--------------------- Result: \(dateDifference.year ?? 0) years \(dateDifference.month ?? 0) months and \(dateDifference.day ?? 0) days")
        } else {
            print("--------------------- No result")
        }
    

    Output is: Result: 10 years 1 months and 18 days

提交回复
热议问题