我有一个UIDatePicker
,用于将当前选中的日期存储到文本字段中。我想要另一个文本字段来计算一个人(作为一个整体int)的年龄,这取决于输入的日期,例如“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?
}
答案 0 :(得分:1)
在您完成输入日期设置后,您现在可以根据今天的日期计算年龄。您可以阅读如何使用以下链接计算日期间隔
Objective C - calculating the number of days between two dates
或
答案 1 :(得分:1)
你可以试试这个
- (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];
}