Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 960
Brock Woolf Avatar asked Jul 24 '09 20:07

Brock Woolf


People also ask

What are the number of days in each month?

The months are either 28, 29, 30, or 31 days long. The Gregorian calendar is divided into 12 months. Each month has either 28, 30, or 31 days during a common year, which has 365 days.

Which months have 30 days and 31?

April, June, and November. Thirty days hath September, April, June, and November, all the rest have thirty-one.


1 Answers

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.

like image 84
Alex Rozanski Avatar answered Oct 11 '22 21:10

Alex Rozanski