-(void)timeSearch{
//time search
self.dateView = [[UIView alloc]initWithFrame:CGRectMake(0, 80, SCREENWIDTH, 216)];//初始化一个日期存放view
[self.view addSubview:_dateView];
self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 216)];
self.datePicker.backgroundColor = [UIColor groupTableViewBackgroundColor];
self.datePicker.userInteractionEnabled = YES;
[self.datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged ];
[_dateView addSubview:self.datePicker];
//重点:UIControlEventValueChanged
//设置显示格式
//默认根据手机本地设置显示为中文还是其他语言
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文显示
self.datePicker.locale = locale;
self.datePicker.datePickerMode = UIDatePickerModeDate;
//当前时间创建NSDate
// NSDate *localDate = [NSDate date];
//在当前时间加上的时间:格里高利历
// NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
//设置时间
[offsetComponents setYear:0];
[offsetComponents setMonth:0];
[offsetComponents setDay:5];
self.search = [UIButton buttonWithType:UIButtonTypeCustom];
self.search.frame = CGRectMake(self.view.frame.size.width - 40, 20, 30, 30);
[self.search setTitle:@"完成" forState:UIControlStateNormal];
self.search.titleLabel.font = [UIFont systemFontOfSize:14];
[self.search setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[self.search addTarget:self action:@selector(keyi) forControlEvents:UIControlEventTouchUpInside];
self.search.userInteractionEnabled = YES;
[_dateView addSubview:self.search];
}
-(void)dateChanged:(id)sender{
UIDatePicker control = (UIDatePicker)sender;
NSDate* date = control.date;
NSLog(@"dateChanged响应事件:%@",date);
//NSDate格式转换为NSString格式
NSDate *pickerDate = [self.datePicker date];// 获取用户通过UIDatePicker设置的日期和时间
NSDateFormatter *pickerFormatter = [[NSDateFormatter alloc] init];// 创建一个日期格式器
[pickerFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *dateString = [pickerFormatter stringFromDate:pickerDate];
//打印显示日期时间
NSLog(@"格式化显示时间:%@",dateString);
_workTF.text = dateString;
}
最后再你需要的时候调用 :timeSearch即可。