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

First create an NSDate for the given year and month:

let dateComponents = NSDateComponents()
dateComponents.year = 2015
dateComponents.month = 7

let calendar = NSCalendar.currentCalendar()
let date = calendar.dateFromComponents(dateComponents)!

Then use the rangeOfUnit() method, as described in Number of days in the current month using iPhone SDK?:

// Swift 2:
let range = calendar.rangeOfUnit(.Day, inUnit: .Month, forDate: date)
// Swift 1.2:
let range = calendar.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)

let numDays = range.length
print(numDays) // 31

Update for Swift 3 (Xcode 8):

let dateComponents = DateComponents(year: 2015, month: 7)
let calendar = Calendar.current
let date = calendar.date(from: dateComponents)!

let range = calendar.range(of: .day, in: .month, for: date)!
let numDays = range.count
print(numDays) // 31

Updated for Swift 3.1, Xcode 8+, iOS 10+

let calendar = Calendar.current
let date = Date()

// Calculate start and end of the current year (or month with `.month`):
let interval = calendar.dateInterval(of: .year, for: date)! //change year it will no of days in a year , change it to month it will give no of days in a current month

// Compute difference in days:
let days = calendar.dateComponents([.day], from: interval.start, to: interval.end).day!
print(days)

Tags:

Swift