1.
//添加时间选择器
UIDatePicker *date = [[UIDatePickeralloc]init];
//设置只显示中文
[date setLocale:[NSLocalelocaleWithLocaleIdentifier:@"zh-CN"]];
//设置只显示日期
date.datePickerMode = UIDatePickerModeDate;
2.
//创建工具条
UIToolbar *toolbar = [[UIToolbaralloc]init];
//设置颜色
toolbar.barTintColor = [UIColorgrayColor];
toolbar.frame = CGRectMake(0, 0, screenWidth, 44);
UIBarButtonItem *item0=[[UIBarButtonItemalloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpacetarget:nilaction:nil];
UIBarButtonItem *item=[[UIBarButtonItemalloc]initWithTitle:@"完成"style:UIBarButtonItemStylePlaintarget:selfaction:@selector(click)];
toolbar.items = @[item0,item];
3.
UITextField *startTimeText = [[UITextFieldalloc]initWithFrame:CGRectMake(0,0,320,40];
//点击文本框是,弹出日期选择器
startTimeText.inputView =date;
//设置文本输入框键盘的辅助视图
startTimeText.inputAccessoryView=toolbar;
startTimeText.delegate =self;
[self addSubview:startTimeText];
UITextField *endTimeText = [[UITextFieldalloc]initWithFrame:CGRectMake( 0,50,320,40)];
//点击文本框是,弹出日期选择器
endTimeText.inputView =date;
//设置文本输入框键盘的辅助视图
endTimeText.inputAccessoryView=toolbar;
endTimeText.delegate =self;
[self addSubview:endTimeText];
4.
#pragma mark 开始编辑
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
_textField = textField;
}
5.
#pragma mark 选中日期
-(void)click
{
//获取日期控件的日期
NSDate *selected = [datedate];
//设置格式
NSDateFormatter *dateFormatter = [[NSDateFormatteralloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSString *destDateString = [dateFormatter stringFromDate:selected];
//将日期放入输入框
_textField.text = destDateString;
//收起日期控件
[_textField resignFirstResponder];
//计算日期,起算时间,终止时间都有值
if(startTimeText.text.length > 0 &&endTimeText.text.length > 0){
NSInteger days = [selfdateCalculation:startTimeText.textendTime:endTimeText.text];
if(days > 0){
}else{
[self initHud:@"终止时间要大于起算时间"yOffset:100];
}
}
}
6.
#pragma mark 日期计算
-(NSInteger)dateCalculation:(NSString *)start endTime:(NSString *)end
{
//实例化一个NSDateFormatter对象
NSDateFormatter *dateFormatter = [[NSDateFormatteralloc]init];
//设定时间格式,这里可以设置成自己需要的格式,但是一定要与上面的格式一样
[dateFormattersetDateFormat:@"yyyy-MM-dd"];
NSDate *startTime =[dateFormatterdateFromString:start];
NSDate *endTime =[dateFormatterdateFromString:end];
NSCalendar *gregorian = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsignedint unitFlags =NSDayCalendarUnit;
NSDateComponents *comps = [gregoriancomponents:unitFlags fromDate:startTime toDate:endTime options:0];
NSInteger days = [compsday];
return days;
}