-1

How to get weekOfMonth value from given date. Today "2021-19-12" Dec 19th come under 4th week But passing any date value, how to get week number specific to date month.

kiran
  • 4,285
  • 7
  • 53
  • 98
  • I guess you mean 2021-12-19, the 19th day of the 12th month of year 2021. Why is that in the 4th week of December? What dates are part of the 1st week of December? What dates are part of the 4th week? – rob mayoff Dec 19 '21 at 03:45

1 Answers1

2

You can ask a Calendar for the .weekOfMonth component of a Date. Example:

import Foundation

let calendar = Calendar(identifier: .gregorian)
for day in 1 ... 31 {
    let date = calendar.date(
        from: DateComponents(
            era: 1,
            year: 2021,
            month: 12,
            day: day,
            hour: 12,
            minute: 0,
            second: 0
        )
    )!
    print(day, calendar.component(.weekOfMonth, from: date))
}

Output:

1 1
2 1
3 1
4 1
5 2
6 2
7 2
8 2
9 2
10 2
11 2
12 3
13 3
14 3
15 3
16 3
17 3
18 3
19 4
20 4
21 4
22 4
23 4
24 4
25 4
26 5
27 5
28 5
29 5
30 5
31 5
rob mayoff
  • 375,296
  • 67
  • 796
  • 848