192
LESSON 15 Working With Dates anD times
Normally the TimeSpan’s ToString method displays a value in the format d.hh:mm:ss.fffffff.
In this example, you use
string.Format to display the elapsed time in the format hh:mm:ss.ff.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them within the Lesson15 folder.
Lesson Requirements
Create the form shown in Figure 15-1. In addition to the controls that are visible, give the
form a Timer with Interval = 1. Initially disable the Stop button.
When the user clicks the Start button, start the
Timer, disable the Start button, and enable
the Stop button.
When the user clicks the Stop button, stop the
Timer, enable the Start button, and disable the
Stop button.
When the
Timer’s Tick event fires, display the elapsed time in the format hh:mm:ss.ff.
Hints
TimeSpan
doesn’t use the same formatting characters as a DateTime, so for example, you
can’t simply use a format string such as
hh:mm:ss.ff. Instead use the TimeSpan properties
to get the elapsed hours, minutes, seconds, and milliseconds and then format those values.
Step-by-Step
Create the form shown in Figure 15-1. In addition to the controls that are visible, give the
form a Timer with Interval = 1. Initially disable the Stop button.
1. Add the Start and Stop buttons and a Label to the form as shown in Figure 15-1. Set
the Stop button’s
Enabled property to False.
2. Add a Timer and set its Interval property to 1 millisecond. (This is much faster than
your computer can actually fire the
Timer’s Click event, so the Timer will run as
quickly as it can.)
When the user clicks the Start button, start the
Timer, disable the Start button, and enable
the Stop button.
1. To remember the time when the user clicked the Start button, create a DateTime field
named
StartTime.
// The time when the user clicked Start.
private DateTime StartTime;
596906c15.indd 192 4/7/10 12:33:00 PM