ProblemYou want to access the year, month, and day numbers from a Date. SolutionSample code folder: Chapter 07\DateParts Use the Year, Month, and Day properties of the Date. DiscussionThese three properties provide a direct route to a Date's date information. Each returns an integer that can be used in further computations. The following code demonstrates these properties in action: Dim rightNow As Date = Now Dim yearNow As Integer = rightNow.Year Dim monthNow As Integer = rightNow.Month Dim dayNow As Integer = rightNow.Day Dim results As String = String.Format( _ "Year: {1}{0}Month: {2}{0}Day: {3}{0}", _ vbNewLine, yearNow, monthNow, dayNow) MsgBox(results) Figure 7-7 shows the system's current date numbers as displayed by the message box in this sample code. Figure 7-7. Extracting year, month, and day numbers from a Date variableThese properties are read-only, so while they work well for extracting the date values, they are not appropriate for assigning a new date to a Date variable. (As explained in Recipe 7.9, Date variables can be set to specific dates, and they can be modified to new dates by adding amounts of time to them.) See AlsoRecipe 7.8 discusses how to access the hour, minute, and second numbers from a Date. Assigning a specific date and/or time to a new Date variable is covered in Recipe 7.9, while Recipes 7.12 and 7.13 discuss assigning a new date to an existing Date variable. |