[英]Swift DateComponents weekOfMonth returns wrong value
I'm working on a calendar view (Cocoa macOS app) that shows the current month.我正在开发一个显示当前月份的日历视图(Cocoa macOS 应用程序)。 When I try to calculate the week number for a given date, I get different results based on the calendar and locale.当我尝试计算给定日期的周数时,我会根据日历和语言环境得到不同的结果。
For January 1st, 2021, some calls return week 0
, others week 1
:对于 2021 年 1 月 1 日,一些电话返回week 0
,另一些返回第week 1
:
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let jan2021 = formatter.date(from: "2021-01-01")!
var deCalendar = Calendar(identifier: .gregorian)
deCalendar.locale = Locale(identifier: "de_de")
var usCalendar = Calendar(identifier: .gregorian)
usCalendar.locale = Locale(identifier: "en_us")
var deIsoCalendar = Calendar(identifier: .iso8601)
deIsoCalendar.locale = Locale(identifier: "de_de")
var usIso = Calendar(identifier: .iso8601)
usIso.locale = Locale(identifier: "en_us")
deCalendar.component(.weekOfMonth, from: jan2021) // 0
deIsoCalendar.component(.weekOfMonth, from: jan2021) // 0
usCalendar.component(.weekOfMonth, from: jan2021) // 1 ??
usIso.component(.weekOfMonth, from: jan2021) // 0
January 1st, 2021 is a Friday so I would expect that the "week of month" is 0
(or 1
, depending on if the particular API is zero-based or not). 2021 年 1 月 1 日是星期五,所以我预计“月份中的一周”为0
(或1
,具体取决于特定的 API 是否从零开始)。
For February 1st, 2021, which is a Monday, all calls above return week 1
!对于 2021 年 2 月 1 日,即星期一,所有高于week 1
的电话都将返回!
Just for kicks, Jan 31st, 2021: the us/gregorian calendar returns "week 6", all others "week 4".只是为了好玩,2021 年 1 月 31 日:美国/公历返回“第 6 周”,所有其他日历返回“第 4 周”。
Bug?, feature?, what am I missing?错误?,功能?,我错过了什么?
For reference:以供参考:
It depends on 2 things in a particular calendar:这取决于特定日历中的两件事:
minimumDaysInFirstWeek
firstWeekday
If you look at calendars you used如果您查看您使用的日历
deCalendar: minimumDaysInFirstWeek=4, firstWeekday=2
deIsoCalendar: minimumDaysInFirstWeek=4, firstWeekday=2
usCalendar: minimumDaysInFirstWeek=1, firstWeekday=1
usIso: minimumDaysInFirstWeek=4, firstWeekday=2
So 3 calendars require at least 4 days to consider it a first week, and they start from Monday (day 2 in US locale).所以 3 个日历需要至少 4 天来考虑它的第一周,它们从星期一开始(美国地区的第 2 天)。 Hence 3-day week is not going to be considered a first week.因此,为期 3 天的一周不会被视为第一周。
Calendar 3 has only 1 day requirement for the week, hence even 1-day is a week.日历 3 对一周只有 1 天的要求,因此即使 1 天也是一周。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.