When you need to put together a full date/time value from a combination of its specific parts, you can overload the Date object's constructors and assign the necessary date/time value parts to it. This tip shows how to perform the functionality.
Putting together a date/time value
There is more than one way to put together a date/time value in VB.NET. Listing A shows different ways of achieving the same functionality.
- The first message box will show: dtDate1: 1/2/2007 12:00:00 A.M.
- The second message box will show: dtDate2: 1/2/2007 12:00:00 A.M.
- The third message box will show: dtDate3: 2/3/2007 3:01:59 A.M.
- The fourth message box will show: dtDate4: 2/3/2007 3:01:59 P.M.
Notes about the example
To set the value of the variable dtDate1, I utilize the # sign to set the date to 1/2/2007. Since the time is not specified, the system will assign the time 12:00:00 A.M. by default. (If you had specified #1/2/2007 3:59:00 PM#, the time assigned would have been 3:59:00 P.M.)
To set the value of the variable dtDate2, I utilize the Date object, passing to it the same date values as for dtDate1. The result is the same; dtDate2 shows exactly the same date as dtDate1 and, since I skipped the time, the time is also set by default to 12:00:00 A.M.
To set the value of the variable dtDate3, I provide full information including the time. Notice that I use military time to set it to 3:00:00 A.M.
To set the value of the variable dtDate4, I use the same date and time as in dtDate3, but I use 15:00:00 for the hour, which results in 3:00:00 P.M.
Miss a tip?
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!