0

Im making a works holiday/vacation day booking app. I have an extension that works out the total number of days between 2 NSDates, it works great, but I do not know how to remove all weekend days from the total.

Can you help please?

extension NSDate {
    func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone     timeZone: NSTimeZone? = nil) -> Int {
        let calendar = NSCalendar.currentCalendar()
        if let timeZone = timeZone {
            calendar.timeZone = timeZone
        }
        var startDate: NSDate?, endDate: NSDate?
        calendar.rangeOfUnit(.Day, startDate: &startDate, interval: nil, forDate: self)
        calendar.rangeOfUnit(.Day, startDate: &endDate, interval: nil, forDate: toDateTime)
        let difference = calendar.components(.Day, fromDate: startDate!, toDate: endDate!, options: [])
        return difference.day
    }
}
ThundercatChris
  • 481
  • 6
  • 25

1 Answers1

4

I found this. It works out the number of weekend days between 2 NSDates

func numberOfWeekendsBeetweenDates(startDate startDate:NSDate,endDate:NSDate)->Int{
    var count = 0
    let oneDay = NSDateComponents()
    oneDay.day = 1;
    // Using a Gregorian calendar.
    let calendar = NSCalendar.currentCalendar()
    var currentDate = startDate;
    // Iterate from fromDate until toDate
    while (currentDate.compare(endDate) != .OrderedDescending) {
       let dateComponents = calendar.components(.Weekday, fromDate: currentDate)
        if (dateComponents.weekday == 1 || dateComponents.weekday == 7 ) {
            count++;
        }
        // "Increment" currentDate by one day.
        currentDate = calendar.dateByAddingComponents(oneDay, toDate: currentDate, options: [])!
    }
    return count
}
ThundercatChris
  • 481
  • 6
  • 25