小编典典

如何使用swift查找给定月份和年份的天数

swift

我想查找给定月份和年份的总天数。示例:我想
查找年份= 2015,月份= 7的总天数


阅读 663

收藏
2020-07-07

共1个答案

小编典典

首先NSDate为给定的年份和月份创建一个:

let dateComponents = NSDateComponents()
dateComponents.year = 2015
dateComponents.month = 7

let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)!

然后使用该rangeOfUnit()方法,如 使用iPhone SDK的当月天数中所述?

// Swift 2:
let range = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)
// Swift 1.2:
let range = calendar.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)

let numDays = range.length
print(numDays) // 31

Swift 3(Xcode 8)更新:

let dateComponents = DateComponents(year: 2015, month: 7)
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!

let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
print(numDays) // 31
2020-07-07