Recipe 7.9. Creating a Date or Time Value from Its Parts


Problem

You want to create a Date variable and assign it a specific date, a specific time of day, or both, but all you have are the individual components, such as the year, month, and day.

Solution

Sample code folder: Chapter 07\SerialDate

Use one of the overloaded Date constructors to assign date and time numbers as the variable is created.

Discussion

You can hardcode a date and/or a time in your application by delimiting the text rep-resentation with a pair of number sign ( #) characters. Here's a line of code that assigns a hardcoded date of July 4, 1776 to a date variable named theFourth:

 theFourth = #7/4/1776# 

As shown, theFourth is assigned a time value of zero, which occurs during the first second of the day, just after midnight as the date changes from the third to the fourth of July. The sample block of code that follows shows how to assign a specific time in addition to a specific date. The first line sets the date variable thirdOfJuly to the last second of the day:

 Dim thirdOfJuly As Date = #7/3/1776 11:59:59 PM# Dim fourthOfJuly As New Date(1776, 7, 4) Dim inTheMorning As New Date(1776, 7, 4, 9, 45, 30) MsgBox( _    "The 3rd and 4th of July, 1776…" & _    vbNewLine & vbNewLine & _    "#7/3/1776 11:59:59 PM# … " & _    thirdOfJuly.ToString & vbNewLine & _    "New Date(1776, 7, 4) … " & _    fourthOfJuly.ToString & vbNewLine & _    "New Date(1776, 7, 4, 9, 45, 30) … " & _    inTheMorning.ToString) 

The second and third lines of this example show how to assign a date and a date/time combination to a date variable in a more dynamic way. Rather than a hardcoded date-and-time literal, integer variables containing Year, Month, Day, Hour, Minute, and Second values can be passed to the Date constructor to assign a moment of time to the Date variable as it is created. Figure 7-9 shows the results of these date and time assignments, as displayed by the message box at the end of the sample code.

Figure 7-9. Different ways to assign specific dates and times to Date variables


Another approach to adjusting a Date variable's date and time is to add quantities of time to it. For example, a freshly dimensioned but unassigned Date variable contains the default date and time of midnight, January 1, 1 AD. You could add 1,775 years, 6 months, and 3 days to the Date variable to adjust it to July 4, 1776. The various date and time addition methods are explained and demonstrated in Recipe 7.12.




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