Recipe 7.8. Extracting Hour, Minute, and Second Numbers from a Date Value


Problem

You want to access the hours, minutes, or seconds from a Date.

Solution

Sample code folder: Chapter 07\TimeParts

Use the Hour, Minute, and Second properties of the Date instance.

Discussion

These properties are similar to the Year, Month, and Day properties of the Date object, but they extract and return the time of the day parts of the Date rather than the date parts. Like the date parts, these time parts of the Date are read-only. The following code shows how to access these properties:

 Dim rightNow As Date = Now Dim hourNow As Integer = rightNow.Hour Dim minuteNow As Integer = rightNow.Minute Dim secondNow As Integer = rightNow.Second Dim millisecondNow As Integer = rightNow.Millisecond Dim results As String = String.Format( _    "Hour: {1}{0}Minute: {2}{0}Second: " & _    "{3}{0}Millisecond: {4}", vbNewLine, _    hourNow, minuteNow, secondNow, millisecondNow) MsgBox(results) 

The Millisecond property also appears in this code. As of this writing, this property's resolution isn't all that great, although it's possible that in the future the milliseconds value will become more accurate. If you need true millisecond timing, use the Stopwatch object described in Recipe 7.6. Even so, the Millisecond property does provide greater accuracy than just to the nearest second.

Figure 7-8 shows the results of the above sample code as displayed by the message box.

Figure 7-8. Extracting hour, minute, second, and millisecond numbers from a Date


See Also

Recipe 7.7 discusses how to extract the year, month, and day numbers from a Date.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net