我有一个UIDatePicker
将当前选择的日期存储到文本字段中的。我想要另一个文本字段,用于根据输入的日期来计算一个人(作为一个整体)的年龄,例如“ 15”。但不确定如何做到这一点。谁能向我指出正确的方向。到目前为止,这就是我所拥有的。
-(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?
}
你可以试试这个
- (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];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句