我试图用户使用当前时间的DateTimePicker
验证所选日期,因此用户无法选择小于当前时间的时间,如下所示
if (DTP_StartTime.Value.TimeOfDay < DateTime.Today.TimeOfDay)
{
MessageBox.Show("you cannot choose time less than the current time",
"Message",
MessageBoxButtons.OK,
MessageBoxIcon.Information,
MessageBoxDefaultButton.Button1,
MessageBoxOptions.RtlReading);
}
但它现在显示为测试目的,我试图显示消息,看看这些条件的价值,发现DateTime.Today.Date
值是00:00:00
MessageBox.Show(DTP_StartTime.Value.TimeOfDay +" <> "+ DateTime.Today.TimeOfDay);
这是验证时间的正确方法吗?
DateTime.Today返回当前日期。如果你想要当前时间,你应该使用DateTime.Now
。
DateTime
值可以直接比较,它们不必转换为字符串。
至于验证,只是不允许用户通过在显示表单之前将DateTimePicker.MinimumDateTime属性设置为DateTime.Now
来选择过去的时间,例如:
DTP_SessionDate.MinimumDateTime=DateTime.Now;
用户仍然有可能花费太长时间输入时间并输入过去几秒钟或几分钟的时间。你仍然可以通过设置未来最少的1-2分钟来解决这个问题:
DTP_SessionDate.MinimumDateTime=DateTime.Now.AddMinutes(1);
无论如何,您可以使用代码验证代码中的值
if(DTP_SessionDate.Value < DateTime.Now)
{
MessageBox.Show("you cannot choose time less than the current time",
...);
}
但更好的选择是使用您使用的堆栈的验证功能。所有.NET堆栈,Winforms,WPF,ASP.NET都通过验证器,验证属性或验证事件提供输入验证
User Input validation in Windows Forms解释了可用于验证Windows窗体堆栈上的输入的机制。
这些事件与错误提供程序一起用于显示通常在数据输入表单中显示的感叹号和错误消息。
DateTimePicker有一个Validating event,可用于验证用户输入并防止用户输入过去的任何值。事件文档中的示例可以适用于此:
private void DTP_SessionDate_Validating(object sender,
System.ComponentModel.CancelEventArgs e)
{
if(DTP_SessionDate.Value < DateTime.Now)
{
e.Cancel = true;
DTP_SessionDate.Value=DateTime.Now;
// Set the ErrorProvider error with the text to display.
this.errorProvider1.SetError(DTP_SessionDate, "you cannot choose time less than the current time");
}
}
private void DTP_SessionDate_Validated(object sender, System.EventArgs e)
{
// If all conditions have been met, clear the ErrorProvider of errors.
errorProvider1.SetError(DTP_SessionDate, "");
}
文章How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component和该部分中的其他文章解释了该控件的工作原理以及如何将其与其他控件结合使用
更新
如果您只想验证时间,可以使用DateTime.TimeOfDay
属性:
if(DTP_SessionDate.Value.TimeOfDay < DateTime.Now.TimeOfDay)
你不应该使用Date
,因为它只代表“DATE”,而不是“TIME”。您要使用的属性称为Now
,其中还包括时间。
if(DTP_SessionDate.Value < DateTime.Now)
{ ... }
更新
根据要求,如果您只使用当天的时间,您可以像这样参考:
if(DTP_SessionDate.Value.TimeOfDay < DateTime.Now.TimeOfDay)
{ ... }
DateTime.Today
没有关于时间的信息。只有约会。然而,DateTime.Now
包含有关时间的信息。
根据Microsoft Docs,这是DateTime返回的内容。
但是,您可以使用DateTime.Now
来获取您的日期和时间。