代码之家  ›  专栏  ›  技术社区  ›  sam

DateTimePicker时间验证

  •  0
  • sam  · 技术社区  · 7 年前

    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);
    

    这是确认时间的正确方法吗?

    3 回复  |  直到 7 年前
        1
  •  1
  •   Panagiotis Kanavos    7 年前

    日期时间。今天返回当前值 . 如果需要当前时间,则应使用 DateTime.Now .

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

    验证 ,只是不允许用户通过设置 DateTimePicker.MinimumDateTime 属性到 日期时间。现在 在显示窗体之前,例如:

    DTP_SessionDate.MinimumDateTime=DateTime.Now;
    

    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)
    
        2
  •  1
  •   Tatranskymedved    7 年前

    你不应该和警察一起工作 Date Now ,也包括时间。

    if(DTP_SessionDate.Value < DateTime.Now)
    {  ... }
    

    根据要求,如果您只使用一天中的某个时间,您可以这样引用它:

    if(DTP_SessionDate.Value.TimeOfDay < DateTime.Now.TimeOfDay)
    {  ... }
    

    DateTime.Today DateTime.Now 但是包括时间信息。

        3
  •  0
  •   Akaino    7 年前

    根据 Microsoft Docs

    但是,您可以使用 DateTime.Now 来确定你的日期和时间。

    推荐文章