Home > Blockchain >  How to get week of month from given date
How to get week of month from given date

Time:12-19

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.

CodePudding user response:

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
  • Related