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

后端 未结 8 639
庸人自扰
庸人自扰 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:21

    In extension format, using self to be able to return the number of days more dynamically (Swift 3).

    extension Date {
    
    func getDaysInMonth() -> Int{
        let calendar = Calendar.current
    
        let dateComponents = DateComponents(year: calendar.component(.year, from: self), month: calendar.component(.month, from: self))
        let date = calendar.date(from: dateComponents)!
    
        let range = calendar.range(of: .day, in: .month, for: date)!
        let numDays = range.count
    
        return numDays
    }
    
    }
    

提交回复
热议问题