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 ...
Get Stephens' Visual Basic® Programming 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.