Is there a way to determine if a year has a leap month in Swift?

家住魔仙堡 提交于 2021-02-10 06:14:23

问题


I see that DateComponents has an Instance Property isLeapMonth. It appears to be a setter property. What I'd really like to know is given a year, is a month a leap month. Is this possible in the API, or do I need to implement my own algorithm to do so? Many thanks in advance.


回答1:


You can check if the first day of the month in question, when set to leap, is a valid date or not:

func isLeap(month: Int, year: Int, era: Int, calendar: Calendar) -> Bool {
    var components = DateComponents()
    components.era = era
    components.year = year
    components.month = month
    components.day = 1
    components.isLeapMonth = true

    return components.isValidDate(in: calendar)
}

// The Chinese year that begins in 2017
isLeap(month: 5, year: 34, era: 78, calendar: Calendar(identifier: .chinese)) // false
isLeap(month: 6, year: 34, era: 78, calendar: Calendar(identifier: .chinese)) // true

// The Chinese year that begins in 2020
isLeap(month: 3, year: 37, era: 78, calendar: Calendar(identifier: .chinese)) // false
isLeap(month: 4, year: 37, era: 78, calendar: Calendar(identifier: .chinese)) // true

According to this list, there are a few calendar systems that use leap month as the date correction mechanism. The Chinese calendar is the one I'm more familiar with. You can cross-reference it against the list of leap months in the Chinese calendar



来源:https://stackoverflow.com/questions/41318604/is-there-a-way-to-determine-if-a-year-has-a-leap-month-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!