我想根据当前时间设置具体时间& datepicker时间。
如果用户选择下午3:01则直接到下午3:30, 下午3:20然后下午3:45, 3:35Pm然后下午4:00。 如果是下午5点,那么下午5点15分。
因此,根据3:00,3:15,3:30,3:45,4:00,用户将获得时间选择,等等...
我已经实现了这个&当我去6:01Pm或将来的任何时间比它工作正常,除了我不能切换回5:01Pm(当前时间是下午3:00)
任何解决方案或可能性问题?
请尝试以下代码。
- (void)viewDidLoad {
[super viewDidLoad];
[self.datePicker addTarget:self action:@selector(datechanged) forControlEvents:UIControlEventValueChanged];
}
NSDate *date = [self.datePicker date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSMinuteCalendarUnit | NSHourCalendarUnit |NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:date];
NSInteger minute = [components minute];
NSInteger hour = [components hour];
if ([components minute] == 0)
{
[components setMinute:15];
}
else
{
NSInteger result = (minute / 15);
if (result == 0)
{
[components setMinute:30];
}
else if(result == 2 || result == 1)
{
[components setMinute:45];
}
else if (result == 3)
{
[components setMinute:60];
}
}
NSDate *newDate = [calendar dateFromComponents: components];
[self.datePicker setMinimumDate:newDate];
[self.datePicker reloadInputViews];
答案 0 :(得分:1)
您可以像这样设置日期更改方法,允许用户设置日期。
- (IBAction)datechanged:(UIDatePicker *)sender {
NSDate *date = [self.datePicker date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitMinute | NSCalendarUnitHour |NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:date];
NSInteger minute = [components minute];
NSInteger hour = [components hour];
NSLog(@"%li",(long)hour);
if ([components minute] == 0)
{
[components setMinute:15];
}
else
{
NSInteger result = (minute / 15);
if (result == 0)
{
[components setMinute:30];
}
else if(result == 2 || result == 1)
{
[components setMinute:45];
}
else if (result == 3)
{
[components setMinute:60];
}
}
NSDate *newDate = [calendar dateFromComponents: components];
NSLog(@"%@",newDate);
//[self.datePicker setMinimumDate:newDate];
[self.datePicker setDate:newDate];
[self.datePicker reloadInputViews];
}
更新1
您可以在viewDidLoad
方法中设置最短日期(表示不允许的过去时间)。
- (void)viewDidLoad {
[super viewDidLoad];
[self.datePicker addTarget:self action:@selector(datechanged) forControlEvents:UIControlEventValueChanged];
[self.datePicker setMinimumDate:[NSDate date]];
}
我的帮助,
HTH,享受编码!!