Get the month as a NSNumber from NSDate
How would I get the month as a NSNumber from开发者_Go百科 a NSDate object? Not the current month but the month of the object
You should use NSCalendar
for this purpose as the month of a date is dependant of the calendar being used. This will be the Gregorian calendar most of the time, but ah let's be super-correct. :)
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents comps = [cal components:NSMonthCalendarUnit fromDate:myDate];
NSLog(@"The month is: %d", [comps month]);
Something like this would be a quick and dirty way:
NSInteger month = [[date descriptionWithCalendarFormat:@"%m"
timeZone:nil
locale:nil] integerValue];
I have used the NSDateFormatter to extract the month component of the date:
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3600];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSLog(@"Month %d", [[dateFormatter stringFromDate:date] intValue]);
精彩评论