How do I find the number of days in given month and year using swift

后端 未结 8 647
庸人自扰
庸人自扰 2020-12-05 04:06

I want to find the total number days on given month and year. Example: I want to find total number of days on year = 2015, month = 7

8条回答
  •  情书的邮戳
    2020-12-05 04:19

    Swift 2.0

    func getDaysInMonth(month: Int, year: 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(NSCalendarUnit.Day, fromDate: startDate, toDate: endDate, options: NSCalendarOptions.MatchFirst)
    
        return diff.day
    }
    
    let days = getDaysInMonth(4, year: 2015) // April 2015 has 30 days
    print(days) // Prints 30
    

    Swift 1.2

    func getDaysInMonth(month: Int, year: 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(NSCalendarUnit.CalendarUnitDay, fromDate: startDate, toDate: endDate, options: NSCalendarOptions.allZeros)
    
        return diff.day
    }
    
    let days = getDaysInMonth(4, 2015) // There were 30 days in April 2015
    println(days) // Prints 30
    

提交回复
热议问题