NSDateComponents returns 错误的工作日

NSDateComponents returns wrong weekday

如果您运行此代码:

// January 16th 2015 10:20 AM in Amsterdam
var date = NSDate(timeIntervalSince1970: 1421400000)

var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MMM"

let calendar = NSCalendar.currentCalendar()
calendar.firstWeekday = 2 // default when region == Netherlands

let units = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit
    | NSCalendarUnit.WeekOfMonthCalendarUnit | NSCalendarUnit.DayCalendarUnit
    | NSCalendarUnit.WeekdayCalendarUnit

// Loop days in January
for day in 1...14 {

    // select day in month
    var components = calendar.components(units, fromDate: date)
    components.day = day

    // get day and components
    let _date = calendar.dateFromComponents(components)!
    var _components = calendar.components(units, fromDate: _date)

    // retrieve characteristics
    let weekOfMonth = _components.weekOfMonth
    let dayOfWeek = _components.weekday
    let month = _components.month

    println("\(formatter.stringFromDate(_date)) is day \(dayOfWeek) of week \(weekOfMonth) of month \(month) \n")
}

你可能会回来:

01-Jan is day 5 of week 1 of month 1
02-Jan is day 6 of week 1 of month 1
03-Jan is day 7 of week 1 of month 1
04-Jan is day 1 of week 1 of month 1
05-Jan is day 2 of week 2 of month 1
06-Jan is day 3 of week 2 of month 1
07-Jan is day 4 of week 2 of month 1
.... 

那些工作日是错误的。

不仅 1 月 1 日应该是第 4 天(星期四),而且 1 月 3 日似乎是第 1 周的第 7 天,而 1 月 4 日似乎是第 1 天也很奇怪同一周。

显然我在这里做错了,谁能帮助我?

当您删除 calendar.firstWeekday = 2 行时,您将得到:

01-Jan is day 5 of week 1 of month 1
02-Jan is day 6 of week 1 of month 1
03-Jan is day 7 of week 1 of month 1
04-Jan is day 1 of week 2 of month 1
05-Jan is day 2 of week 2 of month 1
06-Jan is day 3 of week 2 of month 1
07-Jan is day 4 of week 2 of month 1
....

这更有意义,但我真的需要一周的第一天在这里是星期一..

我已经建立了一个演示项目供您自己测试此行为。 https://github.com/tiemevanveen/NSDateComponentsTest/tree/master


正如 sha 指出的那样,如果您的一周不是从星期日开始,components.weekday 也不会改变。奇怪的是 components.weekOfMonth 当你的一周从星期一开始时确实发生了变化..

解决我的问题

另一个问题的 answer 让我找到了一种方法来找到所需的工作日,如果日历的一周不是从星期日开始的话。

dayOfWeek = calendar.ordinalityOfUnit(.WeekdayCalendarUnit, inUnit: .WeekCalendarUnit, forDate: _date)

该代码也可用于查找月份中的第几周或月份本身:

dayOfWeek = calendar.ordinalityOfUnit(.WeekdayCalendarUnit, inUnit: .WeekCalendarUnit, forDate: _date)
month = calendar.ordinalityOfUnit(.MonthCalendarUnit, inUnit: .YearCalendarUnit, forDate: _date)

一切正确。如果你看Apple Documentation。 您可以看到 1 是星期日,2 - 是星期一,依此类推。所以 5 是预期的星期四。