How to subtract date components?

爱⌒轻易说出口 提交于 2019-12-05 00:28:00
Tj3n

Try this, you have to get the date first then subtract again from it:

var dayComp = DateComponents(day: -6)
let date = Calendar.current.date(byAdding: dayComp, to: Date())
Calendar.current.component(.weekday, from: date!)

For that first you need to get that date using calendar.date(byAdding:value:to:) and then get day number from it.

extension Date {
    func getDateFor(days:Int) -> Date? {
         return Calendar.current.date(byAdding: .day, value: days, to: Date())
    }
}

Now simply use thus function and get your days.

if let date = Date().getDateFor(days: -6) {
    print(Calendar.current.component(.weekday, from: date))
}

you can use calendar and date components and put everything in a Date extension, something like:

(Swift 4.1)

extension Date {
    func removing(minutes: Int) -> Date? {
        let result =  Calendar.current.date(byAdding: .minute, value: -(minutes), to: self)
        return result
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!