Difference between 2 dates in weeks and days using swift 3 and xcode 8

前端 未结 4 2118
情话喂你
情话喂你 2020-12-05 02:13

I am trying to calculate the difference between 2 dates (one is the current date and the other from datepicker) in weeks and days then displaying the result on a label, that

4条回答
  •  情书的邮戳
    2020-12-05 02:58

    Swift 4

    testing using Xcode Version 9.2

    • combining the above two answers that helps me

    Use the following method to get the string by the difference between two dates the idea is to localize the words weeks/ days /minutes by the format.

    func getTimeComponentString(olderDate older: Date,newerDate newer: Date) -> (String?)  {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .full
    
        let componentsLeftTime = Calendar.current.dateComponents([.minute , .hour , .day,.month, .weekOfMonth,.year], from: older, to: newer)
    
        let year = componentsLeftTime.year ?? 0
        if  year > 0 {
            formatter.allowedUnits = [.year]
            return formatter.string(from: older, to: newer)
        }
    
    
        let month = componentsLeftTime.month ?? 0
        if  month > 0 {
            formatter.allowedUnits = [.month]
            return formatter.string(from: older, to: newer)
        }
    
        let weekOfMonth = componentsLeftTime.weekOfMonth ?? 0
        if  weekOfMonth > 0 {
            formatter.allowedUnits = [.weekOfMonth]
            return formatter.string(from: older, to: newer)
        }
    
        let day = componentsLeftTime.day ?? 0
        if  day > 0 {
            formatter.allowedUnits = [.day]
            return formatter.string(from: older, to: newer)
        }
    
        let hour = componentsLeftTime.hour ?? 0
        if  hour > 0 {
            formatter.allowedUnits = [.hour]
            return formatter.string(from: older, to: newer)
        }
    
        let minute = componentsLeftTime.minute ?? 0
        if  minute > 0 {
            formatter.allowedUnits = [.minute]
            return formatter.string(from: older, to: newer) ?? ""
        }
    
        return nil
    }
    

    Here is how you can use

        let nowDate = Date()
        let endDate = Date().addingTimeInterval(12345678)
    
        let string =  String.getTimeComponentString(olderDate: nowDate, newerDate: endDate)!
        print(nowDate)
        print(endDate)
        print(string)
    
    • Output

    • 2018-03-08 08:11:22 +0000
    • 2018-07-29 05:32:41 +0000
    • 4 months

提交回复
热议问题