iOS 开发时间选择器datePicker

-(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即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>