Date Time

The Visual Basic Date keyword has always supported a structure of both date and time. You can, in fact, declare date values using both the DateTime and Date types. Note that internally Visual Basic no longer stores a date value as a Double; however, it provides key methods for converting the current internal date representation to the legacy Double type. The ToOADate and FromOADate methods support backward compatibility during migration from previous versions of Visual Basic.

Visual Basic also provides a set of shared methods that provides some common dates. The concept of shared methods is described in more detail in the next chapter, which covers object syntax, but, in short, shared methods are available even when you don't create an instance of a class. For the DateTime structure, the Now method returns a Date value with the local date and time. This method has not been changed from Visual Basic 6.0, but the Today and utcNow methods have been added. These methods can be used to initialize a Date object with the current local date, or the date and time based on Universal Coordinated Time (also known as Greenwich Mean Time), respectively. You can use these shared methods to initialize your classes, as shown in the following code sample:

Private Sub Dates() Dim dtNow = Now() Dim dtToday = Today()

TextBox1.Text = dtNow & Environment.NewLine

TextBox1.Text &= dtToday.ToShortDateString & Environment.NewLine

TextBox1.Text &= DateTime.UtcNow() & Environment.NewLine Dim dtString = #12/13/2009# TextBox1.Text &= dtString.ToLongDateString() End Sub

Code snippet from Forml

Running this code results in the output shown in Figure 2-7. As noted earlier, primitive values can be assigned directly within your code, but many developers seem unaware of the format for doing this with dates. Another key feature of the Date type is the capability to subtract dates in order to determine a difference between them. The subtract method is demonstrated later in this chapter, with the resulting Timespan object used to output the number of milliseconds between the start and end time of a set of commands.

Was this article helpful?

0 0

Post a comment