从日期计算中排除日期

Exclude dates from date calculation

我想计算两个日期之间的时间。我一直在使用 DateComponentsFormatter,它非常适合在所有 languages/regions/calendars.

中正确输出

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

您可以使用 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

}