问题
I have an NSDate that I get from a UIDatepicker.
IBOutlet UIDatePicker *dueDate;
NSDate *selectedDate = [dueDate date];
How do I retrieve the month from dueDate
in the form of an int
? (1 for Jan, 2 for Feb, etc.)
回答1:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSMonthCalendarUnit fromDate:[dueDate date]];
NSInteger month = [components month];
回答2:
use -[NSCalendar components:fromDate:]
for instance the example here:
http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html
回答3:
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] initWithDateFormat:@"%m" allowNaturalLanguage:NO] autorelease];
int month = [[dateFormat stringFromDate:dueDate] intValue];
来源:https://stackoverflow.com/questions/727696/uidatepicker-and-nsdate