How to get number of weeks by month in year?

独自空忆成欢 提交于 2019-12-13 09:55:18

问题


I want a function that will return an array of week numbers for current month in current year.

For example if the current month is August, 2015 it will return [32, 33, 34, 35, 36]. If month is February, 2015 it will return [6, 7, 8, 9].

Is there a way how can I get this?

In apple docs NSCalendar class has an option to get the number of current week in year but It's not what I need.


回答1:


As already mentioned NSCalendar has a method rangeOfUnit:inUnit:forDate:. The proper calendar units are CalendarUnitWeekOfYear and CalendarUnitMonth

The result might be different for the locale and first weekday of the week settings.

let calendar = NSCalendar.currentCalendar()
let weekRange = calendar.rangeOfUnit(NSCalendarUnit.CalendarUnitWeekOfYear, inUnit: .CalendarUnitMonth, forDate: NSDate())
let weekArray = Array(weekRange.location..<weekRange.location + weekRange.length)

Swift 3:

let calendar = Calendar.current
let weekRange = calendar.range(of: .weekOfYear, in: .month, for: Date())



回答2:


NSCalendar doesn't give any api directly to get the number of weeks in a month. You have to work around with NSDateComponents and NSDate too.

I can give you the hints but as Steve suggested, you need to try by yourself first.

Try getting a range, look into NSCalendar's method- rangeOfUnit:inUnit: Think, how you can use this method to get your desired output.



来源:https://stackoverflow.com/questions/32119114/how-to-get-number-of-weeks-by-month-in-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!