Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateComponents of an NSDate

How do I get the NSDateComponents of a single NSDate? I don't want the components of the difference between 2 dates, just the seconds, minutes, hours, day, month and year of a NSDate?

like image 559
cfischer Avatar asked Jun 25 '11 15:06

cfischer


2 Answers

There's an example in the Apple docs, Listing 3: Getting a date’s components:

NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc]                          initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *weekdayComponents =                     [gregorian components:(NSDayCalendarUnit |                                             NSWeekdayCalendarUnit) fromDate:today]; NSInteger day = [weekdayComponents day]; NSInteger weekday = [weekdayComponents weekday]; 

Note that you have to 'or' together the calendar units you want in the call of the components method.

like image 73
martin clayton Avatar answered Oct 04 '22 04:10

martin clayton


using NSCalendar's method:

- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)date

like:

unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit; NSDate *date = [NSDate date];   NSCalendar * cal = [NSCalendar currentCalendar]; NSDateComponents *comps = [cal components:unitFlags fromDate:date]; 
like image 26
Grady Player Avatar answered Oct 04 '22 05:10

Grady Player