我正试图用这个剪切的列出当月的所有Date
let now = Date()
let cal = Calendar.current
let monthRange = cal.range(of: .day, in: .month, for: now)!
let comps = cal.dateComponents([.year, .month], from: now)
var date = cal.date(from: comps)!
var dates: [Date] = []
for _ in monthRange {
dates.append(date)
date = cal.date(byAdding: .day, value: 1, to: date)!
}
print(">>>>>", dates)
但包含上月最后一天和当月最后一天的输出不存在。
[2022-10-31 15:00:00 +0000, 2022-11-01 15:00:00 +0000, 2022-11-02 15:00:00 +0000, 2022-11-03 15:00:00 +0000, 2022-11-04 15:00:00 +0000, 2022-11-05 15:00:00 +0000, 2022-11-06 15:00:00 +0000, 2022-11-07 15:00:00 +0000, 2022-11-08 15:00:00 +0000, 2022-11-09 15:00:00 +0000, 2022-11-10 15:00:00 +0000, 2022-11-11 15:00:00 +0000, 2022-11-12 15:00:00 +0000, 2022-11-13 15:00:00 +0000, 2022-11-14 15:00:00 +0000, 2022-11-15 15:00:00 +0000, 2022-11-16 15:00:00 +0000, 2022-11-17 15:00:00 +0000, 2022-11-18 15:00:00 +0000, 2022-11-19 15:00:00 +0000, 2022-11-20 15:00:00 +0000, 2022-11-21 15:00:00 +0000, 2022-11-22 15:00:00 +0000, 2022-11-23 15:00:00 +0000, 2022-11-24 15:00:00 +0000, 2022-11-25 15:00:00 +0000, 2022-11-26 15:00:00 +0000, 2022-11-27 15:00:00 +0000, 2022-11-28 15:00:00 +0000, 2022-11-29 15:00:00 +0000]
您只需要切换到行">日期.append(日期(""date=cal.date(通过添加:.day,值:1,到:date(";进入环路
func getDaysSimple(for month: Date) -> [Date] {
//get the current Calendar for our calculations
let cal = Calendar.current
//get the days in the month as a range, e.g. 1..<32 for March
let monthRange = cal.range(of: .day, in: .month, for: month)!
//get first day of the month
let comps = cal.dateComponents([.year, .month], from: month)
//start with the first day
//building a date from just a year and a month gets us day 1
var date = cal.date(from: comps)!
//somewhere to store our output
var dates: [Date] = []
//loop thru the days of the month
for _ in monthRange {
//add to our output array...
date = cal.date(byAdding: .day, value: 1, to: date)!
dates.append(date)
//and increment the day
}
return dates
}
print(getDaysSimple(for: .now))
那么输出是这样的:-------
[2022-11-01 18:30:00 +0000, 2022-11-02 18:30:00 +0000, 2022-11-03 18:30:00 +0000, 2022-11-04 18:30:00 +0000, 2022-11-05 18:30:00 +0000, 2022-11-06 18:30:00 +0000, 2022-11-07 18:30:00 +0000, 2022-11-08 18:30:00 +0000, 2022-11-09 18:30:00 +0000, 2022-11-10 18:30:00 +0000, 2022-11-11 18:30:00 +0000, 2022-11-12 18:30:00 +0000, 2022-11-13 18:30:00 +0000, 2022-11-14 18:30:00 +0000, 2022-11-15 18:30:00 +0000, 2022-11-16 18:30:00 +0000, 2022-11-17 18:30:00 +0000, 2022-11-18 18:30:00 +0000, 2022-11-19 18:30:00 +0000, 2022-11-20 18:30:00 +0000, 2022-11-21 18:30:00 +0000, 2022-11-22 18:30:00 +0000, 2022-11-23 18:30:00 +0000, 2022-11-24 18:30:00 +0000, 2022-11-25 18:30:00 +0000, 2022-11-26 18:30:00 +0000, 2022-11-27 18:30:00 +0000, 2022-11-28 18:30:00 +0000, 2022-11-29 18:30:00 +0000, 2022-11-30 18:30:00 +0000]