之前在公司做一个抢单的项目,里面用到一个DatePicker的控件,写个文章记录一下,以后要用,来copy代码
1.设置属性
@property(nonatomic,strong)UIDatePicker*datePicker;
2.做初始化和设置
self.datePicker=[[UIDatePickeralloc]init];
//设置背景色
(1)self.datePicker.backgroundColor=[UIColorgroupTableViewBackgroundColor];
(2)self.datePicker.backgroundColor=[UIColorclearColor];
[self.viewaddSubview:self.datePicker];
//添加事件,当值改变的时候 注意选择UIControlEventValueChanged
[self.datePickeraddTarget:selfaction:@selector(dateChanged:)forControlEvents:UIControlEventValueChanged];
NSLocale*locale =[[NSLocalealloc]initWithLocaleIdentifier:@"zh_CN"];//设置时间的显示格式为中文显示
self.datePicker.locale=locale;
//当前时间创建NSDate
NSDate*localDate =[NSDatedate];
//在当前时间加上的时间:格里高利历
NSCalendar*gregorian =[[NSCalendaralloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents*offsetComponents =[[NSDateComponentsalloc]init];
//设置时间
[offsetComponents setYear:0];
[offsetComponents setMonth:0];
[offsetComponents setDay:6];
[offsetComponents setHour:24];
[offsetComponents setMinute:60];
[offsetComponents setSecond:0];
//设置最大值时间
NSDate*maxDate =[gregorian dateByAddingComponents:offsetComponents toDate:localDateoptions:0];
self.datePicker.minimumDate= localDate;
self.datePicker.maximumDate= maxDate;
[alert.view addSubview:self.datePicker];
3.当datepicker的值改变时候具体的事件
-(void)dateChanged:(id)sender
{
UIDatePicker*control =(UIDatePicker*)sender;
NSDate*date =control.date;
NSLog(@"原来的格式:%@",date);
NSDate*pickerDate=[self.datePicker date];
NSDateFormatter*pickerFormatter = [[NSDateFormatter alloc]init];
//[pickerFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[pickerFormatter setDateFormat:@"MM-dd HH:mm"];
NSString*dateString = [pickerFormatter stringFromDate:pickerDate];
self.dateStr=dateString;
}