Shrestha Ashesh - 1 year ago 115

Swift Question

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 = calendar.date(from: dateComponents)!
let range = calendar.range(of: .day, in: .month, for: date)
let numDays = range.length
print(numDays) // 31
```