从日期计算中排除日期

时间:2018-03-18 22:22:10

标签: ios swift nsdate nsdateformatter nsdatecomponentsformatter

我想计算两个日期之间的时间。我一直在使用DateComponentsFormatter,它非常适合在所有语言/地区/日历中正确输出。

我想添加从此计算中排除周末的功能。它本身似乎不支持这种做法。是否有一个很好的替代方案(本地或第三方库)从计算中删除一组日期?

1 个答案:

答案 0 :(得分:0)

您可以使用Calendar API本机执行此类计算;你只需要手动编写它:

import Foundation

// The nextWeekend API is available only on 10.12 or later.
if #available(OSX 10.12, *) {

let calendar = Calendar(identifier: .gregorian)
let start = calendar.date(from: DateComponents(year: 2018, month: 3, day: 18))!
let end   = calendar.date(from: DateComponents(year: 2018, month: 4, day: 7))!

var total: TimeInterval = 0

// We'll iterate weekends from now until the target end date,
// adding the intervening time from during the week.
var current = start
while current < end {
    guard let weekend = calendar.nextWeekend(startingAfter: current) else {
        break
    }

    if weekend.start > end {
        // Our target end date is before the next weekend; add whatever time is left.
        total += end.timeIntervalSince(current)
        break
    } else {
        // There's >= 1 weekend between now and the target date; add the week in between.
        total += weekend.start.timeIntervalSince(current)
        current = weekend.end
    }
}

let formatter = DateComponentsFormatter()
formatter.allowedUnits = .day
print(formatter.string(from: total)!) // => 16d

}