本文介绍了如何使用swift找到给定月份和年份的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想找到给定月份和年份的总天数.示例:我想找到 year = 2015, month = 7 的总天数
I want to find the total number days on given month and year.Example: I want to find total number of days on year = 2015, month = 7
推荐答案
首先为给定的年月创建一个NSDate
:
First create an NSDate
for the given year and month:
let dateComponents = NSDateComponents()
dateComponents.year = 2015
dateComponents.month = 7
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)!
然后使用 rangeOfUnit()
方法,如当月使用 iPhone SDK 的天数?:
Then use the rangeOfUnit()
method, as described inNumber of days in the current month using 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
这篇关于如何使用swift找到给定月份和年份的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!