获取上个月的天数

时间:2019-06-13 11:18:19

标签: ios swift xcode date

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

  

即=本月是6月,所以我想5月一个月的总数   天(输出= 31)

这是我尝试过的方法,但是没有用。

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

4 个答案:

答案 0 :(得分:1)

这些是用法:

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

答案 1 :(得分:0)

只需使用Calendar.current.range,请在下面查看。

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

let numDays = range.count

答案 2 :(得分:0)

您得到的仅仅是一个月前的日期,要获得当月的天数,您可以再走一步:

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

仅此而已,您的数量就在numberOfDaysInPreviousMonth中。

答案 3 :(得分:0)

尝试以下代码:

let calendar = NSCalendar.current
let currentDate = Date()
let month = calendar.component(.month, from: currentDate)
let year = calendar.component(.year, from: currentDate)
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)

您还可以根据需要更改年份。

希望这会有所帮助。