簡體   English   中英

如何從給定日期獲取月份的星期幾

[英]How to get week of month from given date

如何從給定日期獲取 weekOfMonth 值。 今天“2021-19-12”12 月 19 日屬於第 4 周但傳遞任何日期值,如何獲取特定於日期月份的周數。

您可以向Calendar詢問Date.weekOfMonth組件。 例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM