你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS7技巧 >> Swift計算當月、任意月一共有多少天例子

Swift計算當月、任意月一共有多少天例子

編輯:IOS7技巧
前面給各位整理過一篇關於前一天後一天的計算了,下面我們來看一篇Swift計算當月、任意月一共有多少天例子,希望文章對各位能夠有幫助。

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)天")

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved