正确使用 Apple Foundation Calendar

Using Apple Foundation Calendar properly

我对 Apple Foundations 框架的日历的正确用法有点困惑。

let calendar = Calendar(identifier: .iso8601)
let dayComponent = DateComponents(year: 2019, weekday: 1, weekOfYear: 6)
let date = calendar.date(from: dayComponent)

我需要获取一年中给定一周的第一天。使用上面的代码时,会根据工作日给出以下日期:

//weekday:
//0 -> 08 FEB
//1 -> 09 FEB
//2 -> 03 FEB
//3 -> 04 FEB
//4 -> 05 FEB

为什么工作日在当前周 (6) 从 0 开始,而在增加时切换到第 5 周?

感谢您的帮助。

一些观察:

  1. 当遍历工作日时,您希望从 1 到 7,因为“日、周、工作日、月和年数字通常从 1 开始......”Date and Time Programming Guide: Date Components and Calendar Units. You can use range(of:in:for:), maximumRange(of:), 等等, 以找到可能值的范围。

  2. 从 1 到 7 的工作日值并不表示“一周的第一天”、“一周的第二天”等。它们指的是一周中的特定日期,例如对于 .iso8601,“Sun”为 1,“Mon”为 2,依此类推

  3. 确保在使用 weekOfYear 时使用 yearForWeekOfYear:

    let calendar = Calendar(identifier: .iso8601)
    let firstOfWeek = DateComponents(calendar: calendar, weekOfYear: 6, yearForWeekOfYear: 2019).date!
    
  4. 您的代码在工作日进行迭代。考虑以下代码,它列举了 2019 年第六周(即从 2 月 4 日星期一开始到 2 月 10 日星期日结束的那一周)的所有日期:

    let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: firstOfWeek)!
    let daysOfTheWeek = Dictionary(uniqueKeysWithValues: zip(weekdays, calendar.weekdaySymbols))
    
    for weekday in weekdays {
        let date = DateComponents(calendar: calendar, weekday: weekday, weekOfYear: 6, yearForWeekOfYear: 2019).date!
        print("The", daysOfTheWeek[weekday]!, "in the 6th week of 2019 is", formatter.string(from: date))
    }
    

    这导致:

    The Sun in the 6th week of 2019 is Sunday, February 10, 2019
    The Mon in the 6th week of 2019 is Monday, February 4, 2019
    The Tue in the 6th week of 2019 is Tuesday, February 5, 2019
    The Wed in the 6th week of 2019 is Wednesday, February 6, 2019
    The Thu in the 6th week of 2019 is Thursday, February 7, 2019
    The Fri in the 6th week of 2019 is Friday, February 8, 2019
    The Sat in the 6th week of 2019 is Saturday, February 9, 2019

    这实际上是您的代码所做的,也是您没有看到预期内容的原因。

  5. 如果您想按顺序遍历一周的 7 天,只需获取一周的开始,然后从那里偏移:

    let calendar = Calendar(identifier: .iso8601)
    let startOfWeek = DateComponents(calendar: calendar, weekOfYear: 6, yearForWeekOfYear: 2019).date!
    
    for offset in 0 ..< 7 {
        let date = calendar.date(byAdding: .day, value: offset, to: startOfWeek)!
        print(offset, "->", formatter.string(from: date))
    }
    

    这导致:

    0 -> Monday, February 4, 2019
    1 -> Tuesday, February 5, 2019
    2 -> Wednesday, February 6, 2019
    3 -> Thursday, February 7, 2019
    4 -> Friday, February 8, 2019
    5 -> Saturday, February 9, 2019
    6 -> Sunday, February 10, 2019

  6. 您问的是:

    I need to get the first day of a given week of year.

    这个时候大概不用多说了,就省略工作日吧:

    let startOfWeek = DateComponents(calendar: calendar, weekOfYear: 6, yearForWeekOfYear: 2019).date!
    

另见 Date and Time Programming Guide: Week-Based Calendars