others - IOS - 如何获取上一个月的总天数?

如何获取上一个月的总天数?

换句话说,当前月份是六月,所以,我想要五月的总天数。(输出31 ),

我尝试了这个但不工作。

let PrevDate = Calendar.current.date(byAdding: .month, value: -1, to: Date())

时间:

以下是用法:


let calendar = Calendar.current


let date1 = calendar.date(byAdding: .month, value: -1, to: Date())! // -1 mean previous month



let range = calendar.range(of: .day, in: .month, for: date1)!


let numDays = range.count


print(numDays)



输出:

 
31



 

Calendar.current.range,看看下面。


let range = Calendar.current.range(of: .day, in: .month, for: PrevDate)!



let numDays = range.count




let calendar = Calendar.current



let prevDate = calendar.date(byAdding: .month, value: -1, to: Date())!


let numberOfDaysInPreviousMonth = calendar.range(of: .day, in: .month, for: prevDate)?.count



尝试以下代码:


let calendar = NSCalendar.current


let month = calendar.component(.month, from: Date())


let year = calendar.component(.year, from: Date())


let dateComponents = DateComponents(year: year, month: month - 1)


let date = calendar.date(from: dateComponents)!



let range = calendar.range(of: .day, in: .month, for: date)!


let numDays = range.count


print(numDays)



你也可以根据你的需求改变年份。

希望这个能帮到你。

...