Verifying That a Value Is a Date

Microsoft® Windows® 2000 Scripting Guide

microsoft windows 2000 scripting guide

« Previous | Next »   

In working with dates, it is important to know whether a particular value is actually a date or not. This is especially true when making WMI queries or when working with databases; your script will fail if it attempts to use an invalid date in these situations.

The IsDate function can tell you whether a supplied value is a date. IsDate returns False (0) if the value is not a date and True ( 1) if the value is a date. Date values can be passed using either of the following:

  • Date literals. These are date values enclosed within pound signs (#). This is the recommended way of using dates in scripts because it eliminates the possibility that VBScript will misinterpret the value as being something other than a date. A date literal might look like this:

    #9/3/2002#

  • Date and time formats recognized by your system settings. For example, if your system is set for English (United States), these values are recognized as valid dates:
    • 6/6/2002
    • 6,1,2002
    • 6-1-2002

    However, this value is not recognized as a valid date:

    • 6.1.2002

    If you change your settings to German (Austria), all four values are recognized as dates.

Note

  • To check valid date formats for your computer, open the Regional and Language Options control panel, click Customize, and then click Date.

The following script creates an array of values and then enumerates each item in the array. The script then uses IsDate to determine whether the item represents a valid date and echoes the value and a message indicating that this is actually a date.

DateArray = Array("6/1/2002", "June 1, 2002",  "6", "6/1") For Each dtmDate in DateArray     If IsDate(dtmDate) = 0 Then         Wscript.Echo dtmDate & " is not a valid date."     Else         Wscript.Echo dtmDate & " is a valid date."     End If Next 

When the preceding script runs under CScript, the following information appears in the command window:

6/1/2002 is a valid date. June 1, 2002 is a valid date. 6 is not a valid date. 6/1 is a valid date. 

Note

  • Why is 6/1 a valid date? When using the IsDate function, VBScript tries to construct a plausible date from the value given to it. When it sees a statement that can be interpreted as Month/Day, it automatically appends the current year, resulting in Month/Day/Year. In the preceding script, which was run in the year 2002, that means a value of 6/1/2002, which is a valid date.

send us your feedback Send us your feedback « Previous | Next »   


Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
Microsoft Windows 2000 Scripting Guide(c) Automating System Administration 2003
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 635

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