如何使用swift查找给定月份和年份的天数
我想查找给定月份和年份的总天数。示例:我想
查找年份= 2015,月份= 7的总天数
回答:
首先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
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
以上是 如何使用swift查找给定月份和年份的天数 的全部内容, 来源链接: utcz.com/qa/418533.html