ProblemYou want to access the hours, minutes, or seconds from a Date. SolutionSample code folder: Chapter 07\TimeParts Use the Hour, Minute, and Second properties of the Date instance. DiscussionThese 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 DateSee AlsoRecipe 7.7 discusses how to extract the year, month, and day numbers from a Date. |