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

前端 未结 4 2077
情话喂你
情话喂你 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 03:13

    You are close. Just add .weekOfMonth (meaning "quantity of weeks" according to the API documentation) to the allowed units. Example:

    let now = Date()
    let endDate = now.addingTimeInterval(24 * 3600 * 17)
    
    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.day, .weekOfMonth]
    formatter.unitsStyle = .full
    let string = formatter.string(from: now, to: endDate)!
    
    print(string) // 2 weeks, 3 days
    

    Setting maximumUnitCount = 2 is not necessary because there are only two allowed units.

提交回复
热议问题