天天看點

ios calendar 結構體使用

calendar 是用于存儲計算時間的結構體,可根據具體使用确定其機關,判斷依據等資訊。

其中Identifier 定義如下,可知有陽曆陰曆等計算時間的方法,可根據實際情況選擇。

public enum Identifier {

        /// The common calendar in Europe, the Western Hemisphere, and elsewhere.
        case gregorian

        case buddhist

        case chinese

        case coptic

        case ethiopicAmeteMihret

        case ethiopicAmeteAlem

        case hebrew

        case iso8601

        case indian

        case islamic

        case islamicCivil

        case japanese

        case persian

        case republicOfChina

        /// A simple tabular Islamic calendar using the astronomical/Thursday epoch of CE 622 July 15
        case islamicTabular

        /// The Islamic Umm al-Qura calendar used in Saudi Arabia. This is based on astronomical calculation, instead of tabular behavior.
        case islamicUmmAlQura
    }
           

components可使用open func components(_ unitFlags: NSCalendar.Unit, from startingDate: Date, to resultDate: Date, options opts: NSCalendar.Options = []) -> DateComponents 方法來擷取。其中unit是定義其計算機關,應 與 最後使用機關相同。

另附使用代碼如下

let gregorian = Calendar(identifier: Calendar.Identifier.gregorian)
    let now = Date()
    let components = (gregorian as NSCalendar?)?.components(NSCalendar.Unit.month, from: birthdayPicker.date, to: now, options: [])
    let age:Int! = components?.month
    print("時間\(age)")