如果您要运行此代码:
// 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指出的那样,如果你的一周没有在sSnday上开始,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)