您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

Swift 計算當月或指定月份共有多少天

編輯:iOS 7 技巧

做行事曆、報表統計、帳單週期這類功能時,「這個月有幾天」是最基礎卻也最容易寫錯的問題——大小月、閏年二月都得考慮進去。手寫 if-else 判斷固然可行,但既然有 NSCalendar,就沒必要自己算。本文示範兩種做法。

核心思路

技巧是「算兩個日期的間隔」:把當月 1 號與下個月 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

    // 當月 1 號
    let startComps = NSDateComponents()
    startComps.day = 1
    startComps.month = month
    startComps.year = year

    // 下個月 1 號(12 月要特別把年份 +1)
    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)天")

二、取得指定年月的天數

把 year 與 month 抽成參數,就能查詢任意月份:

// 計算指定月的天數
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)天")

為什麼這樣寫是對的

  • 閏年自動處理。2016 是閏年,上面範例會正確回傳 29;2017 年 2 月則回傳 28。這段邏輯完全由 NSCalendar 依曆法規則處理,不必自己寫「能被 4 整除但不能被 100 整除,或能被 400 整除」那串條件。
  • 跨年邊界要小心。12 月的「下個月」是隔年 1 月,因此必須同時把 month 設為 1、year 加 1。這是最容易漏掉的地方,少了年份遞增就會算出負數或錯誤結果。
  • 用 components 而非日期相減。直接對兩個 NSDate 相減得到的是「秒數」,還得自己換算成天。用 calendar.components(.Day, ...) 才是依曆法意義計算天數,也能避免日光節約時間造成的誤差。

版本提醒

以上程式碼基於舊版 Swift 與 NSCalendar API。在 Swift 3 之後,建議改用 Calendar.current、Date 與 DateComponents,並以 calendar.range(of: .day, in: .month, for: date)

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