最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Swift计算当月、任意月一共有多少天例子
时间:2022-06-25 23:37:45 编辑:袖梨 来源:一聚教程网
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)天")
2,获取指定年月的天数
//计算指定月天数
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)天")
相关文章
- 以闪亮之名店长体验流霞季怎么玩 缘溪临霞套装活动介绍 12-31
- 未定事件簿旧梦新生左然篇怎么玩 旧梦新生左然篇活动介绍 12-31
- 未定事件簿左然破浪远行怎么样 12-31
- 桃源深处有人家行医问诊怎么玩 12-31
- 恋与制作人跨年福利有哪些 恋与制作人跨年福利内容介绍 12-31
- 阴阳师协同对弈大乱斗怎么玩 阴阳师协同对弈大乱斗活动介绍 12-31