I wanted to group a bunch of data by week, so naturally I used DateComponents to get .year, .month, and .weekOfMonth, which got the right data. Then to group them, I tried creating the date using calendar.date(from:). Only, it turns out, when constructing a date, neither .weekOfMonth nor .weekOfYear is used. Is this expected? It must be, I guess, since it must have been this way before NeXT subsumed Apple?
Given that, is there a better (or, rather, working) way to do it?
Not sure I got you right, but on the surface to group days by their respective year/month/week triple I'd use something like this:
struct YearMonthWeek: Hashable { let year, month, week: Int }
var groupedDates: [YearMonthWeek : [Date]] = [:]
let calendar = Calendar(identifier: .gregorian)
let timeZone = TimeZone(secondsFromGMT: 0)!
for _ in 0 ..< 200 {
let time = TimeInterval.random(in: 0...365*24*60*60)
let date = Date(timeIntervalSinceNow: -time)
let components = calendar.dateComponents(in: timeZone, from: date)
let key = YearMonthWeek(year: components.year!, month: components.month!, week: components.weekOfMonth!)
groupedDates[key, default: []].append(date)
}
print(groupedDates)
(obviously needs work IRT respecting current time zone / calendar).