我花了将近一个星期的尝试失败。如何获取当月的最后日期。例如,如果它是非闰年的二月,那么该月的最后一个日期必须是28.如何获得'28'。另一个例子:如果是1月,那么最后一个日期必须是'31'
答案 0 :(得分:5)
有很多方法,其中有两种:
获取下一个1.并减去一天
func lastDayOfMonth1() -> Date
{
let calendar = Calendar.current
let components = DateComponents(day:1)
let startOfNextMonth = calendar.nextDate(after:Date(), matching: components, matchingPolicy: .nextTime)!
return calendar.date(byAdding:.day, value: -1, to: startOfNextMonth)!
}
print(lastDayOfMonth1())
使用range(of:in:for:)
从范围中获取最后一天并相应地设置组件:
func lastDayOfMonth2() -> Date
{
let calendar = Calendar.current
let now = Date()
var components = calendar.dateComponents([.year, .month, .day], from: now)
let range = calendar.range(of: .day, in: .month, for: now)!
components.day = range.upperBound - 1
return calendar.date(from: components)!
}
print(lastDayOfMonth2())