如何在swift中获取当前周的所有日期

gcxthw6b  于 2023-01-29  发布在  Swift
关注(0)|答案(4)|浏览(343)

我正在进行一个应用程序,我需要获得当前周中所有日期的一年中的某一天。为了实现这一点,我正在寻找类似于以下内容的结果(今天是3月23日星期四)

Monday = 79
Tuesday = 80
Wednesday = 81
Thursday = 82
Friday = 83

周六和周日可以包括在内,但我的申请只需要工作日而不是周末。今天是第82天

wqsoz72f

wqsoz72f1#

要获取一周中的工作日,请执行以下操作:

let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today)
let dates = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
    .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }
    .filter { !calendar.isDateInWeekend($0) }

要将其显示为“Thursday = 82”,则为:

let formatter = DateFormatter()
formatter.dateFormat = "eeee' = 'D"
for date in dates {
    print(formatter.string(from: date))
}

或者

let strings = dates.map { formatter.string(from: $0) }

如果你想让它考虑firstWeekday(通常只有当你不再从结果中过滤周末时才需要考虑,因此下面的isDateInWeekend上没有filter):

let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let todaysDayOfWeek = calendar.component(.weekday, from: today)
guard
    let weekdaysRange = calendar.range(of: .weekday, in: .weekOfYear, for: today),
    let index = weekdaysRange.firstIndex(of: calendar.firstWeekday)
else { return }
let weekdays = weekdaysRange[index...] + weekdaysRange[..<index].map { $0 + weekdaysRange.count }
let dates = weekdays.compactMap { calendar.date(byAdding: .day, value: $0 - todaysDayOfWeek, to: today) }
5uzkadbs

5uzkadbs2#

我在调整Rob的解决方案以适应星期一开始的时间时遇到了问题。此解决方案适用于您的calendar.firstWeekday设置。

var calendar = Calendar.autoupdatingCurrent
calendar.firstWeekday = 2 // Start on Monday (or 1 for Sunday)
let today = calendar.startOfDay(for: Date())
var week = [Date]()
if let weekInterval = calendar.dateInterval(of: .weekOfYear, for: today) {
    for i in 0...6 {
        if let day = calendar.date(byAdding: .day, value: i, to: weekInterval.start) {
            week += [day]
        }
    }
}
return week
szqfcxe2

szqfcxe23#

我在Calendar上做了一个小的扩展,这可能对其他寻找功能更强的解决方案的人有帮助。

import Foundation

extension Calendar {
  func intervalOfWeek(for date: Date) -> DateInterval? {
    dateInterval(of: .weekOfYear, for: date)
  }

  func startOfWeek(for date: Date) -> Date? {
    intervalOfWeek(for: date)?.start
  }

  func daysWithSameWeekOfYear(as date: Date) -> [Date] {
    guard let startOfWeek = startOfWeek(for: date) else {
      return []
    }

    return (0 ... 6).reduce(into: []) { result, daysToAdd in
      result.append(Calendar.current.date(byAdding: .day, value: daysToAdd, to: startOfWeek))
    }
    .compactMap { $0 }
  }
}
flmtquvp

flmtquvp4#

你也可以像这样使用enumerateDates:

func getAllDaysOfTheCurrentWeek() -> [Date] {
    var dates: [Date] = []
    guard let dateInterval = Calendar.current.dateInterval(of: .weekOfYear,
                                                           for: Date()) else {
        return dates
    }
    
    Calendar.current.enumerateDates(startingAfter: dateInterval.start,
                                    matching: DateComponents(hour:0),
                                    matchingPolicy: .nextTime) { date, _, stop in
            guard let date = date else {
                return
            }
            if date <= dateInterval.end {
                dates.append(date)
            } else {
                stop = true
            }
    }
    
    return dates
}

相关问题