How can I get the current number of days in the current month using NSDate or something similar in Cocoa touch?
Asked
Active
Viewed 2.8k times
4 Answers
167
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.
Alex Rozanski
- 37,815
- 10
- 68
- 69
-
I think you meant forDate:today – Jorge Israel Peña Jul 24 '09 at 20:55
-
Yes I did, sorry, called it `date` when I was testing it in Xcode. – Alex Rozanski Jul 24 '09 at 20:59
-
1@Moshe. Yes. This can compute the range of any calendar unit in any larger calendar unit. – Rob Napier Dec 21 '11 at 13:40
-
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar]; might be better for you than just [NSCalendar currentCalendar] – coolcool1994 Jun 29 '13 at 18:28
11
Swift syntax:
let date = NSDate()
let cal = NSCalendar(calendarIdentifier:NSCalendarIdentifierGregorian)!
let days = cal.rangeOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitMonth, forDate: date)
Erez Haim
- 967
- 8
- 11
6
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
Josh Sherick
- 2,161
- 3
- 20
- 37