ProblemYou want to know the current time and date. SolutionSample code folder: Chapter 07\SystemDateTime Use Now, which returns the current moment of time from your system clock as a Date value. DiscussionThe Now property returns a Date, which you can store in a Date variable or process directly. There are many properties and methods available to extract information from Dates. The following code demonstrates just a few of them, and the rest of this chapter provides insight into many more: Dim rightNow As Date = Now Dim result As New System.Text.StringBuilder result.AppendLine("""Now""…") result.AppendLine() result.Append("Date: ").AppendLine(rightNow. ToShortDateString) result.Append("Time: ").AppendLine(rightNow.ToShortTimeString) result.Append(" Ticks: ").Append(rightNow.Ticks.ToString) MsgBox(result.ToString()) rightNow is a Date variable used here to grab and store a single value of Now. If Now were to be used repeatedly in the remainder of this code, it's possible that its value could change in the process. In the code shown, this would not be a problem, but if your application might be affected by having the value of Now suddenly change, you should consider assigning its value to a Date variable just once, to freeze the moment in time for further processing. This code uses a StringBuilder to piece together several bits of information extracted from rightNow. The properties ToShortDateString and ToShortTimeString extract the date and time in a readable format. Figure 7-1 shows typical output displayed by the message box at the end of the sample code. Figure 7-1. Basic information about a frozen moment in timeTicks is an interesting property of the Date data type. It represents the number of 100-nanosecond intervals of time elapsed since midnight on January 1 of the year 1 AD. This is a value closely tied to how the date and time are stored internally in a Date variable. The Ticks property is explained in further detail in Recipe 7.3.
|