[英]changing textfield input to the date picked in a UIDatePicker (when value is changed)
[英]use uidatepicker to set textfield value
我有一個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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.