2

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.

Dribbler
  • 4,343
  • 10
  • 33
  • 53

1 Answers1

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

Code Different
  • 90,614
  • 16
  • 144
  • 163