private void dateTimePickerStart_ValueChanged(object sender, EventArgs e)
{
if (!navigatingDateTimePicker) {
/* First set the navigating flag to true so this method doesn't get called again while updating */
navigatingDateTimePicker = true;
/* using timespan because that's the only way I know how to round times well */
TimeSpan tempTS = dateTimePickerStart.Value - dateTimePickerStart.Value.Date;
TimeSpan roundedTimeSpan;
TimeSpan TDBug = dateTimePickerStart.Value - prevTimePicker1;
if (TDBug.TotalMinutes == 59)
{
// first: if we are going back and skipping an hour it needs an adjustment
roundedTimeSpan = TimeSpan.FromMinutes(5 * Math.Floor((tempTS.TotalMinutes - 60) / 5));
dateTimePickerStart.Value = dateTimePickerStart.Value.Date + roundedTimeSpan;
}
else if (dateTimePickerStart.Value > prevTimePicker1)
{
// round up to the nearest interval
roundedTimeSpan = TimeSpan.FromMinutes(5 * Math.Ceiling(tempTS.TotalMinutes / 5));
dateTimePickerStart.Value = dateTimePickerStart.Value.Date + roundedTimeSpan;
} else {
// round down to the nearest interval from prev
roundedTimeSpan = TimeSpan.FromMinutes(5 * Math.Floor(tempTS.TotalMinutes / 5));
dateTimePickerStart.Value = dateTimePickerStart.Value.Date + roundedTimeSpan;
}
navigatingDateTimePicker = false;
}
prevTimePicker1 = dateTimePickerStart.Value;
}
private void dateTimePickerStart_ValueChanged(object sender, EventArgs e)
{
if (!navigatingDateTimePicker) {
/* First set the navigating flag to true so this method doesn't get called again while updating */
navigatingDateTimePicker = true;
/* using timespan because that's the only way I know how to round times well */
TimeSpan tempTS = dateTimePickerStart.Value - dateTimePickerStart.Value.Date;
TimeSpan roundedTimeSpan;
if (dateTimePickerStart.Value > prevTimePicker1) {
// round up to the nearest interval
roundedTimeSpan = TimeSpan.FromMinutes(5 * Math.Ceiling(tempTS.TotalMinutes / 5));
dateTimePickerStart.Value = dateTimePickerStart.Value.Date + roundedTimeSpan;
} else {
// round down to the nearest interval from prev
roundedTimeSpan = TimeSpan.FromMinutes(5 * Math.Floor(tempTS.TotalMinutes / 5));
dateTimePickerStart.Value = dateTimePickerStart.Value.Date + roundedTimeSpan;
}
navigatingDateTimePicker = false;
}
prevTimePicker1 = dateTimePickerStart.Value;
}
7条答案
按热度按时间uqcuzwp81#
可以通过观察ValueChanged事件并覆盖该值来实现。此示例表单运行良好:
lx0bsm1f2#
我对SixOThree的答案做了一点修改,以消除Necromporph发现的bug。应该是这样的:
班上
在构造函数中
事件
nfzehxib3#
或者简单地试试这个:
gjmwrych4#
问题是向上/向下控件会自动递增或递减日期/时间选择器的当前突出显示部分(即年/月/日/小时/等)。
您最好在日期/时间选择器旁边添加自己的向上/向下控件(可能是一个非常小的vscrollbar),并将其连接到日期/时间选择器值的递增/递减五分钟间隔。
carvr3hs5#
我知道这是一篇旧文章,但我根据上面的答案创建了一个更好的解决方案。
班上
在构造函数中
事件
iecba09b6#
你可以把这段代码
之前
thtygnil7#
@Hans Passant只需要处理59就可以正常工作。