开发者

How can I add just the day of a UIDatePicker to a label - e.g. just "28" when the date selected is "28/10/2011" [duplicate]

This question already has answers here: Closed 11 years ago.

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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜