Chapter 15. Working with Dates and Times

One of Visual Basic's more confusing data types is Date. A Date represents a date, a time, or both. For example, a Date variable might represent Thursday April 1, 2011 at 9:15 a.m.

In this lesson, you learn how to work with dates and times. You learn how to create Date variables, find the current date and time, and calculate elapsed time.

Note

The DateTime data type is a synonym for Date.

CREATING DATE VARIABLES

You can initialize a Date variable to a literal value by surrounding it in number signs as shown here:

Dim dueDate As Date = #10/31/2011 1:23:00 PM#

You can also initialize a Date by using the New keyword as in the following code:

Dim dueDate As New Date(2011, 10, 31)

The preceding code uses a year, month, and day to initialize its Date variable, but the Date type lets you use many different kinds of values. The three most useful combinations of arguments specify the following (all as integers):

  • Year, month, day

  • Year, month, day, hour, minute, second

  • Year, month, day, hour, minute, second, milliseconds

You can also add a kind parameter to the end of the second and third of these combinations to indicate whether the value represents local time or UTC time. (Local and UTC times are explained in the next section.) For example, the following code creates a Date representing 12 noon on March 15, 2010 in the local time zone:

Dim idesOfMarch As New Date(2010, 3, 15, 12, 0, 0, DateTimeKind.Local)

LOCAL AND UTC TIME

Windows has several different notions of dates and times. Two of the most important of these are local time and Coordinated Universal Time (UTC).

  • Local time is the time on your computer as it is configured for a particular locale. It's what you and a program's user typically think of as time.

  • UTC time is basically the same as Greenwich Mean Time (GMT), the time at the Royal Academy in Greenwich, London.

For most everyday tasks, local time is fine. If you need to compare data on computers running in different time zones, however, UTC time can make coordination easier. For example, if you want to know whether a customer in New York created an order before another customer created an order in San Salvador, UTC enables you to compare the times without worrying about the customers' time zones.

A Date object's Kind property indicates whether the object represents local time, UTC time, or an unspecified time. When you create a Date, you can indicate whether you are creating a local time or UTC time. If you do not specify the kind of time, Visual Basic assumes you are making an unspecified time.

After you create a Date, the type provides a couple of methods for converting it between local and UTC values. The ToLocalTime method converts a Date object to local time. Conversely, the ToUniversalTime method converts a time to UTC time.

Note

The ToLocalTime and ToUniversalTime methods don't affect a Date if it is already in the desired format. For example, if you call ToLocalTime on a variable that already uses local time, the result is the same as the original variable.

DATE PROPERTIES AND METHODS

The Date type provides many useful properties and methods for manipulating dates and times. Table 15-1 summarizes some of Date's most useful methods. It indicates which methods are shared, meaning you invoke them using the type name, rather than a variable name, as in Date.IsLeapYear(2012).

Table 15.1. TABLE 15-1

METHOD

PURPOSE

Add

Adds a TimeSpan to the Date. The following section of this lesson describes TimeSpan.

AddDays

Adds a specified number of days to the Date.

AddHours

Adds a specified number of hours to the Date.

AddMinutes

Adds a specified number of minutes to the Date.

AddMonths

Adds a specified number of months to the Date.

AddSeconds

Adds a specified number of seconds to the Date.

AddYears

Adds a specified number of years to the Date.

IsDaylightSavingsTime

Returns True if the date and time are within the Daylight Savings Time period for the local time zone.

IsLeapYear

(Shared) Returns True if the indicated year is a leap year.

Parse

(Shared) Parses a string and returns the corresponding Date.

Subtract

Subtracts another Date from this one and returns a TimeSpan. The following section of this lesson says more about TimeSpan.

ToLocalTime

Converts the Date to a local value.

ToLongDateString

Returns the Date in long date format.

ToLongTimeString

Returns the Date in long time format.

ToShortDateString

Returns the Date in short date format.

ToShortTimeString

Returns the Date in short time format.

ToString

Returns the Date in general format.

ToUniversalTime

Converts the Date to a UTC value.

Table 15-2 summarizes the Date's most useful properties.

Table 15.2. TABLE 15-2

PROPERTY

PURPOSE

Date

Gets the Date's date without the time

Day

Gets the Date's day of the month between 1 and 31

DayOfWeek

Gets the Date's day of the week

DayOfYear

Gets the Date's day of the year between 1 and 366 (leap years have 366 days)

Hour

Gets the Date's hour between 0 and 23

Kind

Returns the Date's kind: Local, Utc, or Unspecified

Millisecond

Gets the Date's millisecond

Minute

Gets the Date's minute between 0 and 59

Month

Gets the Date's month between 1 and 12

Now

(Shared) Gets the current date and time

Second

Gets the Date's second between 0 and 59

TimeOfDay

Gets the Date's time of day as a TimeSpan

Today

(Shared) Gets the current date without a time

UtcNow

(Shared) Gets the current UTC date and time

Year

Gets the Date's year

TIMESPANS

A Date represents a point in time (July 20, 1969 at 20:17:40). A TimeSpan represents an elapsed period of time (1 day, 17 hours, 27 minutes, and 12 seconds).

One of the more useful ways to make a TimeSpan is to subtract one Date from another to find the amount of time between them. For example, the following code calculates the time that elapsed between the first and last manned moon landings:

Dim firstLanding As New Date(1969, 7, 20, 20, 17, 40)
Dim lastLanding As New Date(1972, 12, 11, 19, 54, 57)
Dim elapsed As TimeSpan = lastLanding - firstLanding
MessageBox.Show(elapsed.ToString())

The code creates Date values to represent the times of the two landings. It then subtracts the first date from the second to get the elapsed time and uses the resulting TimeSpan's ToString method to display the duration. The following text shows the code's output in the format days.hours:minutes:seconds.

1239.23:37:17

Table 15-3 summarizes the TimeSpan's most useful properties and methods.

Table 15.3. TABLE 15-3

PROPERTY

MEANING

Days

The number of days.

Hours

The number of hours.

Milliseconds

The number of milliseconds.

Minutes

The number of minutes.

Seconds

The number of seconds.

ToString

Converts the TimeSpan into a string in the format days.hours:minutes:seconds.fractionalSeconds

TotalDays

The entire TimeSpan represented as days. For a 36-hour duration, this would be 1.5.

TotalHours

The entire TimeSpan represented as hours. For a 45-minute duration, this would be 0.75.

TotalMilliseconds

The entire TimeSpan represented as milliseconds. For a 1-second duration, this would be 1,000.

TotalMinutes

The entire TimeSpan represented as minutes. For a 1-hour duration, this would be 60.

TotalSeconds

The entire TimeSpan represented as seconds. For a 1-minute TimeSpan, this would be 60.

Note that you can use the + and – operators to add and subtract TimeSpans, getting a new TimeSpan as a result. This works in a fairly obvious way. For example, a 90-minute TimeSpan minus a 30-minute TimeSpan results in a 60-minute TimeSpan.

TRY IT

In this Try It, you use Date and TimeSpan variables to build the stopwatch application shown in Figure 15-1. When the user clicks the Start button, the program starts its counter. When the user clicks the Stop button, the program stops the counter.

FIGURE 15-1

Figure 15.1. FIGURE 15-1

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.

Note

You can download the code and resources for this Try It from the book's web page at www.wrox.com or www.vb-helper.com/24hourvb.html. You can find them within the Lesson15 folder.

Lesson Requirements

In this lesson:

  • 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 Date; 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 Date field named StartTime:

      ' The time when the user clicked Start.
      Private StartTime As Date
    2. Add the following code to the Start button's Click event handler:

      StartTime = Date.Now
      btnStart.Enabled = False
      btnStop.Enabled = True
      tmrElapsed.Enabled = True
  • When the user clicks the Stop button, stop the Timer, enable the Start button, and disable the Stop button.

    1. Add the following code to the Stop button's Click event handler:

      btnStart.Enabled = True
      btnStop.Enabled = False
      tmrElapsed.Enabled = False
  • When the Timer's Tick event fires, display the elapsed time in the format hh:mm:ss.ff.

    1. Use code similar to the following. Notice that the code divides the number of milliseconds by 10 to convert it into hundredths of seconds.

      ' Subtract the start time from the
      ' current time to get elapsed time.
      Dim elapsed As TimeSpan = Date.Now - StartTime
      
      ' Display the result.
      lblElapsed.Text = String.Format(
          "{0:00}:{1:00}:{2:00}.{3:00}",
          elapsed.Hours,
          elapsed.Minutes,
          elapsed.Seconds,
          elapsed.Milliseconds / 10)

Note

Please select Lesson 15 on the DVD to view the video that accompanies this lesson.

EXERCISES

  1. Make a program with a Birth Date TextBox and a Calculate button. When the user enters a birth date and clicks the button, calculate the person's current age and add items to a ListBox that display the age converted into each of days, hours, minutes, and seconds.

  2. Make a program that displays the days of the week for your next 10 birthdays in a ListBox.

  3. Make a program with two TextBoxes for dates and a Button. When the user clicks the Button, the program should calculate the time between the dates and display it in a message box.

  4. Modify the program you built for Exercise 3 to use DateTimePicker controls instead of TextBoxes. To keep things simple, just display the total number of days between the dates. Use the controls' Value properties to get the selected dates. (This control prevents the user from entering invalid dates. Preventing the user from making mistakes is generally a good idea.)

Note

You can find solutions to this lesson's exercises in the Lesson15 folder inside the download available on the book's web site at www.wrox.com or www.vb-helper.com/24hourvb.html.

EXERCISES
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset