有没有办法快速分割两个DateComponents操作数

时间:2019-02-24 06:16:02

标签: swift

我可以得到两个特定日期之间的差,该差等于日期总数。现在,我想将工作天数除以总天数,并以整数形式获取输出。

 @IBAction func go(_ sender: UIButton) {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let task = Habits(context: context)


    //total number of days started here
    //last date
    let ldate = "2019-02-15"
    let dateformatter = DateFormatter()
    dateformatter.dateFormat = "yy-MM-dd"
    let formatedStartDate = dateformatter.date(from: ldate)
    //last date
    //current date
    let cDate = Date()
    task.sDate = cDate
    //current date
    let components = Set<Calendar.Component>([.day])
    let differenceOfDate = Calendar.current.dateComponents(components, from: formatedStartDate!, to: cDate)
    print("difference starts from here!!")
    print(differenceOfDate)
    //total number of days ended here


    //working days
    let wDate = "2019-02-15"
    let wDateFormatter = DateFormatter()
    wDateFormatter.dateFormat = "yy-MM-dd"
    let wformatedStartDate = wDateFormatter.date(from: wDate)
    let wcDate = Date()
    task.sDate = wcDate
    let wcomponents = Set<Calendar.Component>([.day])
    let wdifferenceOfDate = Calendar.current.dateComponents(wcomponents, from: wformatedStartDate!, to: wcDate)
    print("difference starts from here!!")
    print(wdifferenceOfDate)
    let per = differenceOfDate/wdifferenceOfDate //error:Binary operator '/' cannot be applied to two 'DateComponents' 
    //working days ended here
}

1 个答案:

答案 0 :(得分:1)

如果我正确地回答了您的问题,则需要differenceOfDate对象中的日期组成部分。

您可以使用differenceOfDate.dayOptional来获取它,因此需要使用if let进行条件解包。检查以下代码:

let workingDays = 5 //Suppose workingDays is 5.
if let differenceInDay = differenceOfDate.day {
    let divideWithWorkingDay = differenceInDay / workingDays
    print(divideWithWorkingDay) // 1
}