DateTimePicker 时间验证

DateTimePicker Time validation

我正在尝试使用 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);

这是验证时间的正确方法吗?

您不应该使用 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 returns。

但是您可以使用 DateTime.Now 获取日期和时间。

DateTime.Today returns 当前 日期 。如果你想要当前时间,你应该使用 DateTime.Now.

DateTime 值可以直接比较,不必转换为字符串。

至于验证,只是不允许用户select通过将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)