我正在制作一个工作假期/度假日预订应用程序。我有一个扩展,可以计算出2个NSDates之间的总天数,效果很好,但我不知道如何从总数中删除所有周末天数。
你能帮忙吗?
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
}
}
我发现了这个。它计算出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
}