Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

ios - How to get number of weeks by month in year?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...