Number of days in the current month using iOS?

IosDatetimeCocoaCocoa TouchNscalendar

Ios Problem Overview


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

Ios Solutions


Solution 1 - Ios

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.

Solution 2 - Ios

Swift syntax:

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

Solution 3 - Ios

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

Solution 4 - Ios

-[NSCalendar rangeOfUnit:inUnit:forDate:]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrock WoolfView Question on Stackoverflow
Solution 1 - IosAlex RozanskiView Answer on Stackoverflow
Solution 2 - IosErez HaimView Answer on Stackoverflow
Solution 3 - IosJosh SherickView Answer on Stackoverflow
Solution 4 - IosRob NapierView Answer on Stackoverflow