gpt4 book ai didi

swift - 获取从星期一开始的本周日期数组

转载 作者:可可西里 更新时间:2023-11-01 00:38:58 46 4
gpt4 key购买 nike

我目前有这段代码:

public var daysOfWeek: [Date]? {

let calendar = Calendar.current

let today = self
let dayOfWeek = calendar.component(.weekday, from: today)
if let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today){

let days = (weekdays.lowerBound ..< weekdays.upperBound).compactMap {
calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today)
}
return days
}else{
return nil
}
}

这是 Date 对象的扩展。

我需要做同样的事情,但让日历返回一周中从星期一而不是星期日开始的几天。

最佳答案

您只需要使用 iso8601 日历获取一周的第一天,其中第一个工作日是星期一,并向其添加 0 到 6 天。像这样尝试:

extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
}
extension Date {
var startOfWeek: Date {
return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))!
}
var daysOfWeek: [Date] {
let startOfWeek = self.startOfWeek
return (0...6).compactMap{ Calendar.current.date(byAdding: .day, value: $0, to: startOfWeek)}
}
}

Date().daysOfWeek  // ["Aug 13, 2018 at 12:00 AM", "Aug 14, 2018 at 12:00 AM", "Aug 15, 2018 at 12:00 AM", "Aug 16, 2018 at 12:00 AM", "Aug 17, 2018 at 12:00 AM", "Aug 18, 2018 at 12:00 AM", "Aug 19, 2018 at 12:00 AM"]

关于swift - 获取从星期一开始的本周日期数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51825079/

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