Swift获取当前月份所有Date异常:含上月末日期且缺本月末日期
修正Swift代码以获取当月所有Date实例
问题根源
- 仅使用年、月组件生成的日期,受时区影响可能被解析为上月最后一天(例如本地时区比UTC早时,当月1日0点的UTC时间属于上月)
- 循环逻辑缺陷:先添加当前日期再递增,当月有N天时,最后一次循环会停在第N-1天,递增后的第N天无法被加入数组
修正代码
let now = Date() let cal = Calendar.current let monthDayRange = cal.range(of: .day, in: .month, for: now)! let currentYear = cal.component(.year, from: now) let currentMonth = cal.component(.month, from: now) // 明确创建当月第一天的日期,并确保为当天起始时刻 var currentDate = cal.date(from: DateComponents(year: currentYear, month: currentMonth, day: 1))! currentDate = cal.startOfDay(for: currentDate) var monthlyDates: [Date] = [] for _ in monthDayRange { monthlyDates.append(currentDate) currentDate = cal.date(byAdding: .day, value: 1, to: currentDate)! } print(">>>", monthlyDates)
核心优化
- 直接通过
DateComponents指定day:1,精准定位当月第一天 - 调用
startOfDay(for:)消除时区差异带来的日期偏移问题 - 基于正确的初始日期,原循环逻辑可完整覆盖当月所有天数
内容的提问来源于stack exchange,提问作者Marcel Kopera
相关产品推荐
相关产品推荐

