如何检查数组中的连续工作日

时间:2017-08-29 14:04:24

标签: ios arrays swift nsdate

我有一个下面的函数(datesCheck)循环一个日期数组,如果每天有多个条目,则首先删除所有条目,然后检查日期是否在数组中是连续的,返回连续日期的数量当前日期。

func datesCheck(_ dateArray: [Date]) -> Int {
    let calendar = Calendar.current

    let uniqueDates = NSSet(array: dateArray.map { calendar.startOfDay(for: $0) }).sorted {
    ($0 as AnyObject).timeIntervalSince1970 > ($1 as AnyObject).timeIntervalSince1970
    } as! [Date]
         var lastDate = calendar.startOfDay(for: Date())
         var i = 0

     while i < uniqueDates.count && uniqueDates[i].compare(lastDate) == .orderedSame {
              lastDate = (calendar as NSCalendar).date(byAdding: .day, value: -1, to: lastDate, options: [])!
              i += 1
    }
    numberOfConsecutiveDays = i
    return i
}

此功能运作良好,但我只想将此应用于周一至周五的日期,连续日期检查器检查星期五 - 星期一,实际上忽略星期六和星期日。我试图使用calendar.components来实现这一点,但在检查日期是否连续排除时不能找到忽略周末的方法。

 let today = Date()
 let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
 let components = calendar!.components([.weekday], fromDate: today)

 if components.weekday == 2 {
           print("Monday")
 } else {
           print("Monday")
 }

1 个答案:

答案 0 :(得分:1)

几点:

  • 由于您不需要周末,请将其过滤掉

  • 您的函数是非确定性的,因为它使用当前时间(Date())。每次运行的结果在理论上都是不同的。我添加了第二个参数fromDate以使其具有确定性。

func datesCheck(_ dates: [Date], fromDate: Date = Date()) -> Int {
    let calendar = Calendar.current
    let weekdays = dates.map { calendar.startOfDay(for: $0) }
                    .filter { 2...6 ~= calendar.component(.weekday, from: $0) } 
    let uniqueDates = Set(weekdays).sorted(by: >)

    var i = 0       
    var lastDate = calendar.startOfDay(for: fromDate)
    while i < uniqueDates.count && uniqueDates[i] == lastDate {
        switch calendar.component(.weekday, from: uniqueDates[i]) {
        case 2:
            // When the lastDate is a Monday, the previous weekday is 3 days ago
            lastDate = calendar.date(byAdding: .day, value: -3, to: lastDate)!
        default:
            // Otherwise, it's 1 day ago
            lastDate = calendar.date(byAdding: .day, value: -1, to: lastDate)!
        }
        i += 1
    }
    return i
}

测试:

let dates = [
    DateComponents(calendar: .current, year: 2017, month: 8, day: 29).date!,
    DateComponents(calendar: .current, year: 2017, month: 8, day: 28).date!,
    DateComponents(calendar: .current, year: 2017, month: 8, day: 25).date!,
    DateComponents(calendar: .current, year: 2017, month: 8, day: 24).date!,
    DateComponents(calendar: .current, year: 2017, month: 8, day: 22).date!,
    DateComponents(calendar: .current, year: 2017, month: 8, day: 21).date!
]
let today = DateComponents(calendar: .current, year: 2017, month: 8, day: 29).date!
print(datesCheck(dates, fromDate: today)) // 4

代码打印4,因为根据周末规则忽略了第28和第25之间的差距。