简体   繁体   中英

use uidatepicker to set textfield value

I have a UIDatePicker that stores the date currently selected into a textfield. I want another text field that calculates how old a person (as a whole int) would be depending on the date entered, eg "15". but am unsure how to do that. could anyone point me in the right direction please . Here's what I have so far.

-(void)viewDidAppear:(BOOL)animated{
    [birthdayDatePicker addTarget:self
                   action:@selector(dateChanged:)
         forControlEvents:UIControlEventValueChanged];
}

- (void) dateChanged:(id)sender{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateStyle = NSDateFormatterLongStyle;
    birthdayTextField.text = [NSString stringWithFormat:@"%@",
                   [dateFormatter stringFromDate:birthdayDatePicker.date]];
    //look at todays date, subtract date in birthdayTextField to calculate age maybe?

}

just after you finish getting the entered date is set, you can now compute the age based on todays date. you can read on how to compute date intervals using following links

Objective C - calculating the number of days between two dates

or

http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/DatesAndTimes/Articles/dtDates.html

You can try this

- (void) dateChanged:(id)sender{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSString *startdate= [NSString stringWithFormat:@"%@",
                              [dateFormatter stringFromDate: birthdayDatePicker.date]];

    NSDate *End=[dateFormatter dateFromString:[dateFormatter stringFromDate:[NSDate date]]];

    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSYearCalendarUnit
                                                        fromDate:[dateFormatter dateFromString:startdate]
                                                          toDate:End
                                                         options:0];
 birthdayTextField.text=[NSString stringWithFormat:@" %d years old",components.year];

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM