How do I calculate the number of days in this year in Objective C

前端 未结 12 2147
旧巷少年郎
旧巷少年郎 2020-12-06 03:07

How can i calculate the number of days in a year for any calendar, not just gregorian. I have tried this

NSUInteger *days = [[NSCalendar currentCalendar] range

12条回答
  •  广开言路
    2020-12-06 04:03

    Best solution found for this problem using SWIFT 5.3 and Xcode 12.

    Put it into playgrounds, call the checkLeapYear function passing a year into it and play around.

    func checkLeapYear(year: Int) {
        if year % 4 == 0{
            if year % 100 == 0 {
                if year % 400 == 0{
                    print("\(year) is a Leap Year!")
                } else {
                    print("\(year) is NOT a Leap Year!")
                }
            } else {
                print("\(year) is a Leap Year!")
            }
        } else {
            print("\(year) is NOT a Leap Year!")
        }
    }
    

    The algorithm is quite tricky so I suggest you use the following logic when performing it on your own:

    1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
    2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
    3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
    4. The year is a leap year.
    5. The year is not a leap year.

提交回复
热议问题