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, e.g. "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?
}
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];
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments