Brock Woolf
Brock Woolf

Reputation: 47322

Number of days in the current month using iOS?

How can I get the current number of days in the current month using NSDate or something similar in Cocoa touch?

Upvotes: 71

Views: 28209

Answers (4)

Josh Sherick
Josh Sherick

Reputation: 2161

Swift 3 syntax has changed a bit from Erez's answer:

let cal = Calendar(identifier: .gregorian)
let monthRange = cal.range(of: .day, in: .month, for: Date())!
let daysInMonth = monthRange.count

Upvotes: 6

Erez Haim
Erez Haim

Reputation: 1007

Swift syntax:

let date = NSDate()
let cal = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)!
let days = cal.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)

Upvotes: 11

Alex Rozanski
Alex Rozanski

Reputation: 38015

You can use the NSDate and NSCalendar classes:

NSDate *today = [NSDate date]; //Get a date object for today's date
NSCalendar *c = [NSCalendar currentCalendar];
NSRange days = [c rangeOfUnit:NSDayCalendarUnit 
                       inUnit:NSMonthCalendarUnit 
                      forDate:today];

today is an NSDate object representing the current date; this can be used to work out the number of days in the current month. An NSCalendar object is then instantiated, which can be used, in conjunction with the NSDate for the current date, to return the number of days in the current month using the rangeOfUnit:inUnit:forDate: function.

days.length will contain the number of days in the current month.

Here are the links to the docs for NSDate and NSCalendar if you want more information.

Upvotes: 167

Rob Napier
Rob Napier

Reputation: 299703

-[NSCalendar rangeOfUnit:inUnit:forDate:]

Upvotes: 5

Related Questions