Recipe 7.1. Getting the System Date and Time


Problem

You want to know the current time and date.

Solution

Sample code folder: Chapter 07\SystemDateTime

Use Now, which returns the current moment of time from your system clock as a Date value.

Discussion

The 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 time


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

VB 6 Users' Update

VB 6 dates and times are stored in a different internal binary format than the one used in .NET. VB 6 users sometimes access the numerical values of Dates as double-precision numbers, providing a shortcut for some specialized processing. .NET dates are stored as Long integers in an incompatible format. It's best to rewrite your code to use the new Date values, but if you do have old date data that needs to be converted to the new format, use the ToOADate() and FromOADate() functions provided specifically for this purpose.





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