How to subtract date components?

Coder221 picture Coder221 · Dec 30, 2016 · Viewed 11.3k times · Source

As today is Friday, which is 6 according to NSCalendar. I can get this by using the following

Calendar.current.component(.weekday, from: Date())

How do I get weekday component of Saturday last week, which should be 7?

If I do Calendar.current.component(.weekday, from: Date()) - 6 . I am getting 0 which is not valid component.

Answer

Tj3n picture Tj3n · Dec 30, 2016

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!)