A fairly straight forward question, I am trying to figure out how I can get the current number of days in the current month using NSDate or something similar in Cocoa touch. Thanks.
+9
A:
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.
Perspx
2009-07-24 20:29:50
Looks like this will do the trick. Thanks :)
Brock Woolf
2009-07-24 20:34:15
I think you meant forDate:today
Jorge Israel Peña
2009-07-24 20:55:14
Yes I did, sorry, called it `date` when I was testing it in Xcode.
Perspx
2009-07-24 20:59:14