20

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.

Coder221
  • 1,403
  • 2
  • 19
  • 35
  • You want date of last Saturday? – Nirav D Dec 30 '16 at 10:46
  • No, I want component , which is 7, basically I like to know how to subtract components. For example Monday is 2. If I want to know component of day, 3 days before, it is Friday which should be 6. But if I do 2 - 3 , I get -1, which is invalid. Hope I am clear – Coder221 Dec 30 '16 at 10:46
  • You have to get the date then subtract the day from that, not just minus the component – Tj3n Dec 30 '16 at 11:04

3 Answers3

27

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!)
Jack Wilsdon
  • 6,706
  • 11
  • 44
  • 87
Tj3n
  • 9,837
  • 2
  • 24
  • 35
8

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))
}
Nirav D
  • 71,513
  • 12
  • 161
  • 183
2

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
    }
}
Kappe
  • 9,217
  • 2
  • 29
  • 41