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

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

    In order to get number of days and all the dates on given month and year, try this.

    func getAllDates(month: Int, year: Int) -> [Date] {
        let dateComponents = DateComponents(year: year, month: month)
        let calendar = Calendar.current
        let date = calendar.date(from: dateComponents)!
    
        let range = calendar.range(of: .day, in: .month, for: date)!
        let numDays = range.count
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy MM dd"
        formatter.timeZone = TimeZone(abbreviation: "GMT+0:00")
        var arrDates = [Date]()
        for day in 1...numDays {
            let dateString = "\(year) \(month) \(day)"
            if let date = formatter.date(from: dateString) {
                arrDates.append(date)
            }
        }
    
        return arrDates
    }
    

    Usage:

    let arrDatesInGivenMonthYear = getAllDates(month: 1, year: 2018)
    debugPrint(arrDatesInGivenMonthYear)
    //Output: [2018-01-01 00:00:00 +0000, 2018-01-02 00:00:00 +0000, ... , 2018-01-31 00:00:00 +0000]
    
    let numberOfDays = arrDatesInGivenMonthYear.count
    debugPrint(numberOfDays)
    //Output: 31
    

提交回复
热议问题