gpt4 book ai didi

swift - 计算2个NSDates之间的工作日和周末

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:23 27 4
gpt4 key购买 nike

我正在尝试计算 2 个 NSDate 之间的工作日数 + 工作日数,但我似乎找不到合适的解决方案。我目前可以像这样找到 2 个 NSDate 之间的天数:

func reloadData(){
let cal = NSCalendar.currentCalendar()

var daysInt = 0

let days = cal.components(.Day, fromDate: selectedDateTimePointTwo, toDate: selectedDateTimePointOne, options: [])
daysInt = days.day

workDaysLabel.text = "work days: \(daysInt)"
weekendDaysLabel.text = "weekend days: "
}

谁能指出我正确的方向?

最佳答案

首先,如果你使用的是 Swift 2,你应该让 NSDate 符合 Comparable 协议(protocol):

extension NSDate: Comparable { }

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.compare(rhs) == .OrderedAscending
}

其次,您可以使用 Calendar isDateInWeekend 来检查是否有任何日期是周末,并且您可以使用 dateByAddingUnit 在开始日期和结束日期之间添加一天:

创建这些扩展来帮助您:

编辑/更新:Swift 4

extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
}


extension Date {
var isDateInWeekend: Bool {
return Calendar.iso8601.isDateInWeekend(self)
}
var tomorrow: Date {
return Calendar.iso8601.date(byAdding: .day, value: 1, to: noon)!
}
var noon: Date {
return Calendar.iso8601.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
}

和一种计算天数的方法:

func coutDays(from start: Date, to end: Date) -> (weekendDays: Int, workingDays: Int) {
guard start < end else { return (0,0) }
var weekendDays = 0
var workingDays = 0
var date = start.noon
repeat {
if date.isDateInWeekend {
weekendDays += 1
} else {
workingDays += 1
}
date = date.tomorrow
} while date < end
return (weekendDays, workingDays)
}

测试:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let start = DateComponents(calendar: .iso8601, year: 2016).date! // "Jan 1, 2016, 12:00 AM"
let end = DateComponents(calendar: .iso8601, year: 2017).date! // "Jan 1, 2017, 12:00 AM"
print(coutDays(from: start, to: end)) // 105, 261
}
}

关于swift - 计算2个NSDates之间的工作日和周末,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39442576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com