Moh*_*ham 2 objective-c uidatepicker
我的选择器设置:
当前时间
在按钮操作后获取选择器值(以下代码):
//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];
Run Code Online (Sandbox Code Playgroud)问题:
当前时间是下午 6:17
选择器从下午 6:00 开始并显示。
提议:
1.
否则,当前时间高于 6:00 和低于 6:30 表示,则选择器从 6:30 开始。
这是四舍五入到最接近 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
Run Code Online (Sandbox Code Playgroud)
编辑:将模运算符从 \ 更正为 %
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];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1219 次 |
| 最近记录: |