Recipe 7.7. Extracting Year, Month, and Day Numbers from a Date Value


Problem

You want to access the year, month, and day numbers from a Date.

Solution

Sample code folder: Chapter 07\DateParts

Use the Year, Month, and Day properties of the Date.

Discussion

These 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 variable


These 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 Also

Recipe 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.




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

Similar book on Amazon

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