Possible Duplicate:
U开发者_开发知识库IDatePicker and NSDate
Can I do this and how? I simply need to get the day inputted by the user and put it into a label, rather than the whole date (e.g. old: 28/10/2011 new: 28)
Thanks
If your user input is text you will need to start with an NSDateFormatter
and then you can extract the day from the calendar components. (I recommend collecting the date through a UIDatePicker
)
//Start here for a date that is a string
NSString *userinput = @"28/10/2011";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy"];
NSDate *date = [formatter dateFromString:userinput];
[formatter release];
//Start here if you already have an `NSDate` object
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit
fromDate:date];
NSString *dayForLabel = [NSString stringWithFormat:@"%d", [components day]];
Something like this:
NSDate *date = [picker date];
NSCalendar *calendar = [picker calendar];
NSDateComponents *dateComponents = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:date];
NSInteger day = [dateComponents day];
label.text = [NSString stringWithFormat:@"%d", day];
精彩评论