我的选择器设置:
当前时间
按钮操作后获取选择器值(低于代码):
//Begin time
if(date_formate)
date_formate=nil;
date_formate=[[NSDateFormatter alloc] init];
[date_formate setDateFormat:@"hh:mm a"];
txtfldBeginTime.text=[date_formate stringFromDate:time_picker.date];
问题:
当前时间是下午6:17
选择器从下午6:00开始显示。
立论:
1
否则,当前时间在6:00以上且在6:30以下表示,然后选择器从6:30开始。
答案 0 :(得分:3)
以下是最接近30分钟的公式
int remainder = currentMinute % 30;
int rounded = currentMinute + 30-remainder;
// if current minute is 17
// remainder = 17 % 30 == 17
// rounded = 17 + 30-17 == 30
// if current minute is 56
// remainder = 56 % 30 == 26
// rounded = 56+30-26== 60
编辑:从\到%
更正模数运算符EDIT2:抱歉我之前发布的公式不正确。这应该是正确的答案
编辑3:完整代码
- (NSDate *)roundUpToNearestHalfHour:(NSDate *)value {
NSDateComponents *comp = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitCalendar fromDate:value];
NSInteger minute = [comp minute];
int remainder = minute % 30;
int rounded = minute + 30 - remainder;
[comp setMinute:rounded];
return [comp date];
}
答案 1 :(得分:1)
我这样解决了
- (void)viewDidLoad {
[super viewDidLoad];
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
tapGesture.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapGesture];
DoneCancelNumberPadToolbar *toolbar = [[DoneCancelNumberPadToolbar alloc] initWithTextField:self.startTime];
toolbar.delegateLocal = self;
self.startTime.inputAccessoryView = toolbar;
self.endTime.inputAccessoryView = toolbar;
self.pickerStartTime = [[UIDatePicker alloc] init];
self.pickerStartTime.datePickerMode = UIDatePickerModeTime;
[self.pickerStartTime setLocale:[NSLocale localeWithLocaleIdentifier:@"pt_BR"]];
[self.pickerStartTime setMinuteInterval:30];
[self.pickerStartTime addTarget:self action:@selector(dateStartIsChanged) forControlEvents:UIControlEventValueChanged];
self.startTime.inputView = self.pickerStartTime;
}
- (void) dateStartIsChanged {
NSDateComponents *comp = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitCalendar fromDate:self.pickerStartTime.date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"H:mm"];
self.startTime.text = [outputFormatter stringFromDate:[comp date]];
}
答案 2 :(得分:0)
对于那些正在寻找@Tien Dinh的答案但在Swift(Swift 4)中的人。
func roundUpToNearestQuarterHour(date: Date) -> Date{
var comp = Calendar.current.dateComponents(in: TimeZone.current, from: date)
let minute = comp.minute
let remainder = minute % 30;
let rounded = minute + 30 - remainder;
comp.setValue(rounded, for: .minute)
return comp.date
}