[英]Is there any way to divide two DateComponents operands in swift
I can get the difference between two particular dates which will be equal to total number of dates. 我可以得到两个特定日期之间的差,这将等于日期总数。 Now I want to divide working days with total number of days and get output as an integer. 现在,我想将工作日除以总天数,并以整数形式获取输出。
@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
}
If I got your question correctly you want a day component from differenceOfDate
object. 如果我正确地回答了您的问题,那么您需要一个来自differenceOfDate
对象的日组件。
You can get it with differenceOfDate.day
which is Optional
value so you need use if let
for conditional unwrapping. 您可以使用differenceOfDate.day
来获取它,它是Optional
值,因此if let
条件展开, if let
需要使用。 Check below code: 检查以下代码:
let workingDays = 5 //Suppose workingDays is 5.
if let differenceInDay = differenceOfDate.day {
let divideWithWorkingDay = differenceInDay / workingDays
print(divideWithWorkingDay) // 1
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.