Swift - 计算当月、任意月一共有多少天
来源:互联网 发布:福州大学网络教育平台 编辑:程序博客网 时间:2024/04/29 20:11
1,获取当前月天数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//计算当月天数
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
}
1
2
let
days = getDaysInCurrentMonth()
print
(
"本月有\(days)天"
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//计算指定月天数
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
}
1
2
let
days = getDaysInMonth(2016, month: 2)
print
(
"2016年2月有\(days)天"
)
0 0
- Swift - 计算当月、任意月一共有多少天
- 根据日期计算当月有多少天
- 计算某个日期到今天一共有多少年多少月多少日
- C#计算一个月有多少天
- 计算当前月有多少天
- 计算某一月有多少天
- Oracle根据年份和月份,返回该月一共有多少天
- 一共有多少条鱼?
- 中国字一共有多少个?
- 一共有多少个三角形
- 【DP】一共有多少种走法
- freemarker 函数 计算一个月有多少天
- Flex中计算某个月有多少天
- 计算某个月有多少天的方法
- 【技巧】 - 关于计算某个月有多少天 - 黑马程序员
- JS: 如何计算一个月有多少天
- 计算某一年的某一月有多少天。
- JS-如何计算一个月有多少天
- AOP技术基础
- Point类的构造函数
- 09 关于快速排序
- 22 电量变化广播
- hdu5898 odd-even number(数位dp)
- Swift - 计算当月、任意月一共有多少天
- 8-Elementary UDP Sockets
- Zookeeper、Redis分布式锁,实现与区别
- @jsonignoreproperties 是干什么用的
- 使用tinymix进行Acostic测试
- Unity设置物体与屏幕成一定关系
- UNITY之Lua与C#交互
- mybatis之dao的开发
- JAVA进阶----ThreadPoolExecutor机制