gpt4 book ai didi

ios - 枚举一年中每个月的第 N 天

转载 作者:行者123 更新时间:2023-11-28 10:09:49 25 4
gpt4 key购买 nike

在尝试枚举一系列月份的天数时,我得到了意想不到的结果。例如,我想确定 2018 年每个月的第 29 天。由于 2 月没有第 29 天,我预计有 11 个日期:1 月 29 日、3 月 29 日、4 月 29 日等......相反,我只得到 1 月 29 日返回。

粘贴到 Playground 上:

var calendar = Calendar(identifier: .gregorian)
calendar.locale = Locale(identifier: "en_US")
calendar.timeZone = TimeZone(identifier: "America/Chicago")!

let firstOfYear = Date(timeIntervalSince1970: 1514786400)
let endDate = calendar.date(byAdding: .year,
value: 1,
to: firstOfYear,
wrappingComponents: false)!

var components = DateComponents()
components.day = 29 // unexpected results
// components.day = 5 // correct results

var dates = [Date]()

calendar.enumerateDates(startingAfter: firstOfYear,
matching: components,
matchingPolicy: .strict,
using: { (nextDate: Date?, exactMatch: Bool, stop: inout Bool) in

if nextDate?.compare(endDate) == .orderedDescending {
stop = true
return
}

dates.append(nextDate!)
})

dates

请注意,我已经尝试了所有 4 种 matchingPolicy 类型,结果相同。任何人都能够阐明正在发生的事情?似乎枚举在找不到一个月内的日期后停止。创建自己的循环来确定日期是最佳做法吗?

最佳答案

来自 Calendar enumerateDates 的文档:

If an exact match is not possible, and requested with the strict option, nil is passed to the closure and the enumeration ends

这就是为什么您只能获得 1 月 29 日的日期。在请求不存在的日期(例如非闰年的 2 月 29 日)时,使用其他匹配模式效果不佳。

下面的代码给了你想要的结果:

func datesFor(day: Int, year: Int) -> [Date] {
var res = [Date]()
var components = DateComponents(year: year, day: day)
for month in 1...12 {
components.month = month
if let date = Calendar.current.date(from: components) {
// Feb 29, 2018 results in Mar 1, 2018. This check skips such dates
if Calendar.current.date(date, matchesComponents: components) {
res.append(date)
}
}
}

return res
}

print(datesFor(day: 29, year: 2018))

关于ios - 枚举一年中每个月的第 N 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49417499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com