To display the time by using a DateTimePicker control
1. Add a DateTimePicker control to the form, with the default name DateTimePicker1.
2. Double-click the form to switch to the Code Editor.
3. Add the following code to the Form1_Load event handler. This code sets the format of the control to display a time, instead of a date, and lets the user change the time that is displayed.
this.dateTimePicker1.Format = DateTimePickerFormat.Time; this.dateTimePicker1.Width = 100; this.dateTimePicker1.ShowUpDown = true; |
4. Add a Button control to the form, and change the following properties.
Property | Value |
Name | currentTime |
Text | Current Time |
5. Double-click the button to add the default Click event handler.
6. Add the following code to set the time back to the current time.
this.dateTimePicker1.Value = DateTime.Now; |
7. Press F5 to run the program.
8. When the form opens, change the time by selecting the hour, minute, or seconds and click the up or down arrow.
9. Click Current Time to reset the control to the current time.
Отображение времени с помощью элемента управления "DateTimePicker"
1. Добавьте в форму элемент управления DateTimePicker в форму, оставив имя по умолчанию DateTimePicker1.
2. Дважды щелкните форму для переключения в редактор кода.
3. В обработчик событий Form1_Load добавьте следующий код. Этот код установит формат элемента управления для вывода времени, вместо даты, и позволит пользователю изменять отображаемое время.
this.dateTimePicker1.Format = DateTimePickerFormat.Time; this.dateTimePicker1.Width = 100; this.dateTimePicker1.ShowUpDown = true; |
4. Добавьте элемент управления Button в форму и измените следующие свойства.
Свойство | Значение |
Имя | currentTime |
Текст | Текущее время |
5. Дважды щелкните кнопку для добавления обработчика событий по умолчанию Click.
6. Добавьте следующий код для установки времени на текущее.
this.dateTimePicker1.Value = DateTime.Now; |
7. Нажмите клавишу F5 для выполнения программы.
8. После открытия формы измените время, выбрав часы, минуты или секунды, и щелкните стрелку вниз или вверх.
9. Щелкните Текущее время для восстановления текущего времени в элементе управления.
How to: Determine the Span Between Two Dates
This example calculates the difference in days between two dates and constructs a TimeSpan value for that difference.
Example
DateTime oldDate = new DateTime(2002,7,15); DateTime newDate = DateTime.Now; // Difference in days, hours, and minutes. TimeSpan ts = newDate - oldDate; // Difference in days. int differenceInDays = ts.Days; System.Console.WriteLine("Difference in days: {0} ", differenceInDays); System.Console.ReadLine(); |
Compiling the Code
Copy the code and paste it into the Main method of a console application.
Дата добавления: 2022-05-27; просмотров: 123;