Shrestha Ashesh Shrestha Ashesh - 1 year ago 142
Swift Question

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

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

Answer Source

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 beta 2):

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

let range = calendar.range(of: .day, in: .month, for: date)
let numDays = range.length
print(numDays) // 31
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download