Formatting Strings
VBScript provides several functions designed to format strings-and other data types-into specially formatted strings. For example, suppose you have a function that calculates the total up time for a server, and you want to display that information as a percentage. The following script is an example of how VBScript lets you format the output.
Dim iUpHours, iDownHours
iUpHours = InputBox("How many hours has the server " & _
been up?" & _
" Fractional numbers are OK.")
iDownHours = InputBox("How many hours has the server " & _
been down?" & _
" Fractional numbers are OK.")
Dim sResult
sResult = CalcDownPerc(iUpHours, iDownHours)
MsgBox "The server has been down for " & _
sResult & " of the " & _
"time it has been up."
Function CalcDownPerc(iUpHours, iDownHours)
Dim iPerc
iPerc = iDownHours / iUpHours
Dim sDisplay
sDisplay = FormatPercent(iPerc, 4)
CalcDownPerc = sDisplay
End Function
In this example, FormatPercent() is used to format the contents of variable iPerc so that the result has four digits after the decimal place, and the result may have a leading zero before the decimal depending upon the computer's locale settings.
Another popular formatting function is FormatDateTime(). In the next example, suppose that variable dLastLogon contains a user's last logon date.
Dim sDate
sDate = FormatDateTime(dLastLogon, vbShortDate)
This example will display the date in the computer's short date format, which in the U.S. looks like 5/26/2003. Other formats include
vbGeneralDate.
This can display a date, a time, or both. Dates are formatted using the short date format, and times are displayed as a long time. If both parts are included, both parts are displayed.
vbLongDate.
This displays a date using the computer's long date format, such as "Monday, May 26, 2003."
vbShortDate.
This displays a date using the computer's short date format, such as "5/26/2003."
vbLongTime.
This displays a time using the computer's long time format, such as "8:53 A.M."
vbShortTime.
This displays a time using the computer's short time format. This is generally a 24-hour format, such as "13:26" rather than "1:26 P.M."
NOTE
As you'll learn in the next chapter, VBScript stores date and time information in an internal serial number format, so that a date and time together might look something like 857387.5784893. A date by itself might be stored as 859340.0, whereas a time might look like 0.589738. All date and time variables contain both a date and time component, so it's best to use FormatDateTime() to display just the portion you want.
VBScript also includes FormatNumber() and FormatCurrency() functions. You can learn more about these in the VBScript documentation if you need them; I find that they have pretty limited application in common administrative scripts.
|