是否可以从日历组件(Swift 3)获取给定月份和年份的每一天的日期数组
目前,我只想找到一种获得天数的方法,但仅此而已。
目的是开发我的自定义日历,但我坚持这个阶段......
我想写的扩展名如下:
extension Date
{
func getAllDays() -> [Date]
}
或类似的方法:
func getAllDays(month: Int, year: Int) -> [Date]
答案 0 :(得分:2)
最后,我找到了一种方法:
extension Date
{
mutating func addDays(n: Int)
{
let cal = Calendar.current
self = cal.date(byAdding: .day, value: n, to: self)!
}
func firstDayOfTheMonth() -> Date {
return Calendar.current.date(from:
Calendar.current.dateComponents([.year,.month], from: self))!
}
func getAllDays() -> [Date]
{
var days = [Date]()
let calendar = Calendar.current
let range = calendar.range(of: .day, in: .month, for: self)!
var day = firstDayOfTheMonth()
for _ in 1...range.count
{
days.append(day)
day.addDays(n: 1)
}
return days
}
}
用法示例:
let allDays = Date().getAllDays()
输出:
2017-06-01 22:00:00 +0000
2017-06-02 22:00:00 +0000
2017-06-03 22:00:00 +0000
2017-06-04 22:00:00 +0000
...
...
2017-06-30 22:00:00 +0000
答案 1 :(得分:1)
这里有一些更好的代码来做同样的事情
extension Date {
var startOfMonth: Date {
return Calendar.iso8601.date(from: Calendar.iso8601.dateComponents([.year, .month], from: self))!
}
var daysOfMonth: [Date] {
let startOfMonth = self.startOfMonth
let calendar = Calendar.current
let range = calendar.range(of: .day, in: .month, for: self)!
return range.compactMap{ calendar.date(byAdding: .day, value: $0, to: startOfMonth)}
}
}
extension Calendar {
static let iso8601 = Calendar(identifier: .iso8601)
}