Swift - 计算当月、任意月一共有多少天
作者:hangge | 2016-06-06 10:10
1,获取当前月天数
//计算当月天数
func getDaysInCurrentMonth() -> Int {
let calendar = NSCalendar.currentCalendar()
let date = NSDate()
let nowComps = calendar.components([.Year, .Month, .Day], fromDate: date)
let year = nowComps.year
let month = nowComps.month
let startComps = NSDateComponents()
startComps.day = 1
startComps.month = month
startComps.year = year
let endComps = NSDateComponents()
endComps.day = 1
endComps.month = month == 12 ? 1 : month + 1
endComps.year = month == 12 ? year + 1 : year
let startDate = calendar.dateFromComponents(startComps)!
let endDate = calendar.dateFromComponents(endComps)!
let diff = calendar.components(.Day, fromDate: startDate, toDate: endDate,
options: .MatchFirst)
return diff.day
}
测试代码:
let days = getDaysInCurrentMonth()
print("本月有\(days)天")
//计算指定月天数
func getDaysInMonth( year: Int, month: Int) -> Int
{
let calendar = NSCalendar.currentCalendar()
let startComps = NSDateComponents()
startComps.day = 1
startComps.month = month
startComps.year = year
let endComps = NSDateComponents()
endComps.day = 1
endComps.month = month == 12 ? 1 : month + 1
endComps.year = month == 12 ? year + 1 : year
let startDate = calendar.dateFromComponents(startComps)!
let endDate = calendar.dateFromComponents(endComps)!
let diff = calendar.components(.Day, fromDate: startDate, toDate: endDate,
options: .MatchFirst)
return diff.day
}
测试代码:
let days = getDaysInMonth(2016, month: 2)
print("2016年2月有\(days)天")
全部评论(1)
/**
返回月份的天数
*/
func daysCount(year: Int, month: Int) -> Int {
var daysArray = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year % 400 == 0 || year % 100 != 0 && year % 4 == 0 {
daysArray[2] += 1
}
我就是这样写的啊 嘎嘎嘎嘎嘎嘎
return daysArray[month]
}
站长回复:这也是个好办法,多谢提供。