gpt4 book ai didi

ios - 使用 uidatepicker 设置文本字段值

转载 作者:行者123 更新时间:2023-11-29 10:56:22 26 4
gpt4 key购买 nike

我有一个 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];

}

关于ios - 使用 uidatepicker 设置文本字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18118643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com