VBS VBA Working With Dates

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Working With Dates and Times in

VBScript
Posted on January 20, 2009by nilpo
VBScript provides a wide variety of support for working with dates and times. It offers a number
of different functions geared toward retrieving the current date and time, calculating past and
future dates and times, and comparing dates and times.

Since there are so many functions available, the key to learning and use them all is to break
them down into groups based on what they do. This simplified approach will help you to
remember them more easily.

It’s important to understand that VBScript treats dates and times as a numeric sub-type and
provides an actual data type for them. This allows VBScript to perform date and time
calculations more easily.

Dates and times in VBScript are handled according to the VT_Date specification. Among other
things, this determines the range of dates that VBScript will accept, the precision of those dates
and times, and the manner in which they are handled internally. This also means that dates
and times are based upon the system clock as well as the current system’s regional date and
time settings. Scripters should be aware that this creates inherent flaws when working with
dates and times from remote systems and when performing calculations on dates and times
that span multiple time zones.

Finally, scripters should also be aware that VBScript will support nearly every acceptable date
and time format. This means that scripts written in different areas of the world may look very
different. You should know your intended audience very well when implementing dates and
times in your scripts. For instance, does your target audience use a 12 or 24-hour clock? Do
they list dates with the month or day first? What language are weekday and month names
in? Is Sunday the first day of the week or do they use a completely different calendar
altogether?

{mospagebreak title=Retrieving the date and time}


VBScript provides three functions for retrieving the current system date and time. While the
current date and time are considered a single Date value, these functions can return either or
both parts. These values are based on the current system clock, so there can be extreme
variances from system to system.

WScript.Echo Now()
WScript.Echo Date()

WScript.Echo Time()

Output:

9/5/2008 12:59:01 AM

9/5/2008

12:59:01 AM

The Now function returns the current system date and time. The Date and Time functions
return only those portions, respectively. These functions return a Date data type. Internally,
this is handled as a 64-bit signed floating point number. However, when displaying these
values, VBScript will construct a string based on the local short-date and short-time formats as
set by the system’s regional date and time settings.

On my machine, you can see that the United States region uses an MM/DD/YYYY short-date
format and a 12-hour HH:MM:SS short-time format. The actual output you see may be
different if you are using different regional date and time settings than I am.

WScript.Echo CDbl(Now)

WScript.Echo CDbl(Date)

WScript.Echo CDbl(Time)

Output:

39696.040972

39696.000000

0.040972
I mentioned that dates and times in VBScript are 64-bit signed floating point numbers. In
VBScript these are represented by the Double data type. The code above is used to
demonstrate what dates and times look like internally in VBScript. As you can see, they are in
fact a floating point number. The integer portion is used to represent the date, while the
decimal portion represents the time. Supplying a zero value to one of these parts will cause it
to be ignored.

The current date and time is expressed as the number of days that have passed since midnight,
December 30, 1899. At the time of this writing, 36,696 days have passed since that time. The
time portion of this number expresses the current time at a fraction of a day.

WScript.Echo Timer()

VBScript also provides another useful function that is often little used. The Timer function
returns a Double value based on the current system time that indicates the number of seconds
that have passed since midnight. This can be used for performing calculations or timing events
that require accuracy greater than a whole second.

{mospagebreak title=Working with date and time parts}


You may not always wish to return the entire date or time. Your script may only need to know
the current month or day of the week. As a result, VBScript provides a number of different
functions for retrieving date and time parts.

dtmValue = Now()

WScript.Echo Hour(dtmValue)

WScript.Echo Minute(dtmValue)

WScript.Echo Second(dtmValue)

Output:

59
1

The most commonly used of these functions return portions of the current time. The Hour
function returns a number between 0 and 24 that represents the current hour. Note that this
number is independent of whether or not the system uses a 12 or 24-hour clock. The Minute
and Second functions both return a value between 0 and 60, as you might expect. The Second
function always returns a two-digit number, so it may contain a leading zero.

WScript.Echo Day(dtmValue)

WScript.Echo Month(dtmValue)

WScript.Echo MonthName(Month(dtmValue))

WScript.Echo Year(dtmValue)

Output:

September

2008

Similar functions exist for extracting parts of a date. The Day function returns a number
between 1 and 31, indicating the day of the month; the Month function returns a number
between 1 and 12, which represents the month of the year; and the Year function returns a
number indicating the four-digit year. VBScript also provides the MonthName function for
returning the textual month name. This function accepts a single parameter—an integer
indicating the month. It returns a string that varies based upon the local system language.

WScript.Echo Weekday(dtmValue)

WScript.Echo WeekdayName(Weekday(dtmValue))
Output:

Friday

VBScript can also determine the weekday for a specified date. The Weekday function returns a
number between 1 and 7 that indicates the current day of the week. The WeekdayName
function can use this number to return the textual representation of that value. This string
varies depending upon the current system language and local regional and time settings, which
determine what day of the week is first on the calendar.

WScript.Echo DatePart("y", Now)

WScript.Echo DatePart("ww", Now)

Output:

249

36

Finally, VBScript provides another very interesting function. The DatePart function is used to
return parts of a date, much like the functions you’ve just seen. It differs in its flexibility. It
accepts two required parameters. The first is a string that indicates what interval (or date part)
to return. The list of acceptable values can be found in Table 1 below. The second required
parameter is a Date value. In the example above, I’ve used date part to return the number of
days that have passed in the current year and the number of weeks, respectively.

Table 1: Date interval strings

“d” Day

“m” Month

“yyyy” Year
“h” Hour

“n” Minute

“s” Second

“w” Weekday

“q” Quarter

“y” Day of Year

“ww” Week of Year

DatePart also accepts two optional parameters. The first of these determines the day to be
considered the first day of the week. If used, it accepts a constant value from Table 2 below. If
omitted, this value defaults to vbSunday.

Table 2: VBScript WeekDay Constants

Constant Value Description

vbUseSystemDayOfWeek 0 Use NLS API (system) setting

vbSunday 1 Sunday

vbMonday 2 Monday

vbTuesday 3 Tuesday

vbWednesday 4 Wednesday

vbThursday 5 Thursday

vbFriday 6 Friday

vbSaturday 7 Saturday
DatePart optionally accepts a final parameter that specifies the first week of the year. It
accepts a constant value from Table 3 below. If omitted, this defaults to vbFirstJan1.

Table 3: VBScript FirstWeekOfYear Constants

Constant Value Description

vbUseSystem 0 Use NLS API (system) setting

vbFirstJan1 1 The week in which Jan 1 occurs.

vbFirstFourDays 2 The first week having at least 4 days in the new year.

vbFirstFullWeek 3 The first full week of the new year.

{mospagebreak title=Assigning Date values}


VBScript provides support for performing calculations on dates and times and provides a
number of functions to that end. Before you learn how to perform these calculations, it’s
important to understand how to assign date and time values.

dtmValue = #1/31/1976#

dtmValue = #31-1-1976#

dtmValue = #January 31, 1976#

dtmValue = #Jan 31 1976#

dtmValue = #3:01 PM#

You’ve already seen how the Now, Date, and Time functions can be used to assign Date
values. It’s important to realize that you can also assign Date values literally using the number
symbol in much the same way as a double quotation mark indicates a string. Any acceptable
time or date format can be used, and VBScript doesn’t care whether you use a forward slash or
a hyphen to separate date parts.

Leaving any portion of the date or time unspecified will assume the current day. For example,
assigning January 2 to a date will assume January 2 of the current year.
Be very careful when literally assigning dates using the short-date format. VBScript is smart
enough to realize there cannot be 31 months in a year, and it will correctly assign that to the
day portion; however, using numbers 12 and below gets confusing. VBScript assumes that the
local short-date format is used. Thus, providing the date 1/4/2008 in the United States will
assume MM/DD/YYYY format and assign the date January 4, 2008 when you may have intended
April 1, 2008 instead.

Assigning an invalid date (such as February 29, 1900—since 1900 was not a leap year) will result
in a general syntax error. This can make debugging a bit rough. If you are assigning a date
based on user input, it’s a good idea to validate that information to prevent errors.

dtmDate = DateSerial(1976, 1, 31)

dtmTime = TimeSerial(13, 30, 0)

VBScript also provides two functions for creating Date type values based upon integer part
values. The DateSerial function returns a Date. It accepts three parameters: a four-digit year,
an integer month, and an integer day, respectively. The TimeSerial function works similarly and
accepts an integer hour (based on the 24-hour clock), an integer for minutes, and an integer for
seconds.

dtmDate = DateValue("January 31, 1976")

dtmDate = CDate("January 31, 1976")

dtmTime = TimeValue("3:30 PM")

dtmTime = CDate("3:30 PM")

VBS provides two more useful functions for assigning Dates. The DateValue and TimeValue
both create Date types based on formatted strings. Additionally, the CDate function can be
used to convert any sub-type into a Date type. An error will occur if the supplied value cannot
be interpreted as a Date.

WScript.Echo CDate("January 31, 1976 3:30 PM")

WScript.Echo DateValue("January 31, 1976 3:30 PM")

WScript.Echo TimeValue("January 31, 1976 3:30 PM")


Output:

1/31/1976 3:30:00 PM

1/31/1976

3:30:00 PM

The reasons for using DateValue and TimeValue to convert a string instead of CDate may not be
immediately obvious. Consider the example above. CDate is creating a Date value for the
entire supplied string. DateValue and TimeValue will allow you to create Date values containing
only the specified portion of the string while ignoring the rest.

{mospagebreak title=Performing calculations}


Primarily, VBScript provides two different functions for performing Date and Time calculations:
DateAdd, which is used to change a date based on a specified interval; and DateDiff, which is
used to find the interval between two dates.

WScript.Echo DateAdd("m", 1, Now)

WScript.Echo DateAdd("d", -9, Date)

Output:

10/5/2008 4:34:36 AM

8/27/2008

DateAdd returns a Date value. It accepts three parameters. The first is an interval string from
Table 1 below; the second is a number indicating the number of intervals; and the third is a
Date value.

Table 4: Date interval strings

“d” Day
“m” Month

“yyyy” Year

“h” Hour

“n” Minute

“s” Second

“w” Weekday

“q” Quarter

“y” Day of Year

“ww” Week of Year

You can see in the example above how I’ve used DateAdd to return dates based on today. The
first example returns the date one month from today. The second example uses a negative
value to return the date nine days ago.

WScript.Echo DateDiff("d", "1-Apr-64", Now)

Output:

16228

The DateDiff function returns the number of intervals between two dates. It has three required
parameters: the first is an interval string from Table 1 above, while the second and third are the
two Date values to compare. It accepts the same optional parameters as the DatePart function
you saw earlier in this article. In the example above, I’m using DateDiff to calculate the number
of days between today’s date and April 1, 1964.

WScript.Echo #2-Feb-2008# – #20-Jan-2008#

WScript.Echo Date – #1-Jan-2008#


Output:

13.000000

248.000000

Finally, VBScript allows you to perform calculations on Dates directly. If you recall, Dates are
treated internally as Doubles. As a result, VBScript will let you perform arithmetic calculations
on them.

Because the Date data type is a numeric type, Dates can be used in any of VBScript’s
mathematical functions.

Be aware that the result of arithmetic calculations between two or more dates will be of type
Double.

WScript.Echo Int(Now)

WScript.Echo Fix(Now)

Output:

9/5/2008

9/5/2008

While Dates are used as Doubles for numeric calculations, I did notice one interesting
behavior. VBScript’s Int and Fix functions are used to return the integer portion of a floating
number. In both cases, VBScript correctly removes the time portion of a date, but returns the
value as a Date instead of a Double. Apparently, VB correctly recognizes that we supplied a
Date value and kindly sends one back. This got me wondering about VBScript’s behaviors.

dtmNow = Now

WScript.Echo dtmNow – Int(dtmNow)


WScript.Echo dtmNow – Fix(dtmNow)

Output:

0.206192

0.206192

I then decided to see what would happen if I attempted to perform a calculation with those
results. In these examples, I’m using Int and Fix to return the date portion of the current
date. I’m then subtracting that from the result of the Now function which should return the
current time. In both cases, VBScript seems to return a Double.

WScript.Echo TypeName(dtmNow – Int(dtmNow))

Output:

Double

A quick check reveals that it does in fact return a Double. So how about accuracy?

WScript.Echo CDate(dtmNow – Int(dtmNow))

Output:

4:56:55 AM

Sure enough, VBScript’s calculation correctly returns the current time. This further proves how
VBScript handles dates internally as numbers.

{mospagebreak title=Date formats}


VBScript provides a cool function for controlling the display format of dates and times. Its sole
purpose is to return the string representation of a date or time in a specified format.
WScript.Echo FormatDateTime(Now)

WScript.Echo FormatDateTime(Now, vbLongDate)

WScript.Echo FormatDateTime(Now, vbShortDate)

WScript.Echo FormatDateTime(Now, vbLongTime)

WScript.Echo FormatDateTime(Now, vbShortTime)

Output:

9/5/2008 5:31:14 AM

Friday, September 05, 2008

9/5/2008

5:31:14 AM

05:31

The FormatDateTime function has one required parameter, a Date to format. A second
optional parameter is used to determine the format that should be outputted based on a
constant value in the table below. If omitted, vbGeneralDate is used.

Table 5: VBScript Date Format Constants

Constant Value Description

Display a date in short date format. If the date parameter is


vbGeneralDate 0 Now(), it will also return the time, after the date.

Display a date using the local long date format. E.g. Weekday,
vbLongDate 1 Month, Day, Year
Display a date using the local short date format. E.g.
vbShortDate 2 MM/DD/YY

Display a time using the local time format. E.g. hh:mm:ss


vbLongTime 3 AM/PM

vbShortTime 4 Display a time using the 24-hour format: hh:mm.

As I stated earlier in this article, VBScript supports nearly every valid date and time format;
however, its default types are determined by the regional date and time settings of the local
system. From type to time, you may want to change these settings. They can be changed very
easily from within VBScript.

WScript.Echo GetLocale()

SetLocale(1033)

SetLocale("en-us")

Ouput:

1033

The GetLocale function returns an integer representing the current regional code. The
SetLocale function can be used to set the current regional code by either numeric code or its
string abbreviation. Note that the SetLocale function globally affects the local system settings.

‘Start of script:

intRegionalCode = GetLocale()

SetLocale("en-gb")

‘End of script:

SetLocale(intRegionalCode)
The example above demonstrates how you can use the GetLocale and SetLocale functions to
temporarily change the local date and time region for the duration of your script.

You now have all the tools you need to begin working with dates and times in VBScript. In my
next article, I’ll show you how to put these functions to the test by creating a dynamic
calendar. Stick around for a chance to learn by example. Until next time, keep coding!

DXC Technology India Private Limited (formerly CSC Technologies India Private Limited) - Unit 13, Block
2, SDF Buildings, MEPZ SEZ, Tambaram, Chennai 600 045, Tamil Nadu. Registered in India, CIN:
U72900TN2015FTC102489.
DXC Technology Company -- This message is transmitted to you by or on behalf of DXC Technology
Company or one of its affiliates. It is intended exclusively for the addressee. The substance of this
message, along with any attachments, may contain proprietary, confidential or privileged information or
information that is otherwise legally exempt from disclosure. Any unauthorized review, use, disclosure
or distribution is prohibited. If you are not the intended recipient of this message, you are not
authorized to read, print, retain, copy or disseminate any part of this message. If you have received this
message in error, please destroy and delete all copies and notify the sender by return e-mail. Regardless
of content, this e-mail shall not operate to bind DXC Technology Company or any of its affiliates to any
order or other contract unless pursuant to explicit written agreement or government initiative expressly
permitting the use of e-mail for such purpose.

You might also like