如何使用 DateTimePicker 控件显示时间

如果希望应用程序允许用户选择日期和时间,并按指定格式显示该日期和时间,请使用 DateTimePicker 控件。 以下过程演示如何使用 DateTimePicker 控件显示时间。

使用 DateTimePicker 控件来显示时间

  1. Format 属性设置为 Time

    timePicker.Format = DateTimePickerFormat.Time;
    
    timePicker.Format = DateTimePickerFormat.Time
    
  2. DateTimePickerShowUpDown 属性设置为 true

    timePicker.ShowUpDown = true;
    
    timePicker.ShowUpDown = True
    

下面的代码示例演示如何创建一个 DateTimePicker,使用户能够仅选择时间。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TimePickerApplication
{
    public class Form1 : Form
    {
        public Form1()
        {
            InitializeTimePicker();
        }
        private DateTimePicker timePicker;

        private void InitializeTimePicker()
        {
            timePicker = new DateTimePicker();
            timePicker.Format = DateTimePickerFormat.Time;
            timePicker.ShowUpDown = true;
            timePicker.Location = new Point(10, 10);
            timePicker.Width = 100;
            Controls.Add(timePicker);
        }
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }
}
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms

Public Class Form1
    Inherits Form

    Public Sub New()
        InitializeTimePicker()

    End Sub
    Private timePicker As DateTimePicker


    Private Sub InitializeTimePicker()
        timePicker = New DateTimePicker()
        timePicker.Format = DateTimePickerFormat.Time
        timePicker.ShowUpDown = True
        timePicker.Location = New Point(10, 10)
        timePicker.Width = 100
        Controls.Add(timePicker)

    End Sub

    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())

    End Sub
End Class

编译代码

此示例需要:

  • 对 System、System.Data、System.Drawing 和 System.Windows.Forms 程序集的引用。

另请参阅