tags:

views:

162

answers:

3

I have an NSDate object and need an integer of the day. i.e. if we have 25th May 2010, the int should be 25. Is there a simple way to do it?

+3  A: 

Please consider this post on how to get calendar components from an NSDate. Essentially it will look something like:

NSCalendar*       calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents* components = [calendar components:NSDayCalendarUnit
                                           fromDate:myDate];
NSInteger         day = [components day];

(Don't forget memory management for the above.)

fbrereto
+2  A: 

Note that an NSDate is just a timestamp and only has a "day" when considered with respect to a given calendar and time zone. If you want the Gregorian calendar in the current time zone,

NSTimeZone * tz = [NSTimeZone localTimeZone];
CFAbsoluteTime at = CFDateGetAbsoluteTime((CFDateRef)date);
int day = CFAbsoluteTimeGetGregorianDate(at, (CFTimeZoneRef)tz).day;

If you want the UTC day, set tz = nil.

Also, CFAbsoluteTime and NSDate are (as far as I know) based on POSIX time which specifies a 86400-second day, and thus do not handle leap seconds.

tc.
A: 

If you only need the "25" part of an NSDate you can get it from a dateFormatter.

Something like:

NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd"];
NSString *dayInMonthStr = [dateFormatter stringFromDate:today];
int dayInMonth = [dayInMonthStr intValue];
[dateFormatter release];
NSLog(@"Today is the %i. day of the month", dayInMonth);
RickiG