VBScript - Working With Time Values

Applies to TestComplete 14.40, last modified on April 22, 2021

In this topic you will learn how to work with time values in VBScript using the following sections:

Basics

Operations over time values are very similar to operations over dates. Each time value includes a date part and vice versa.

Since the TestComplete scripting engine only supports OLE-compatible data types, the date-time values are implemented as floating-point variant values in a special format. The integer part of this value represents the number of days that have passed since December 30, 1899. The number after the decimal separator is time partition: it represents the fraction of a 24-hour period that has elapsed. However, you do not have to understand what these floating-point values represent. TestComplete provides several routines that help you convert these values to their string representation (see below).

Below are some examples of date-time values and their meaning:

Value Meaning
0.25 December 30, 1899. 6:00 AM
36345.5 July 4, 1999. 12:00 PM
39094.65625 January 12, 2007. 3:45 PM

When you are only working with time values the integer part can be omitted. However the time value can vary more than 24 hours and may result in a date-time value that has an integer part.

Objects and Functions for Working With Time Values

TestComplete has an aqDateTime object that contains methods that can be useful when operating with date-time values.

Method Description
AddHours Adds or subtracts the specified number of hours to (from) the given date.
AddMinutes Adds or subtracts the specified number of minutes to (from) the given date.
AddSeconds Adds or subtracts the specified number of seconds to (from) the given date.
AddTime Adds or subtracts the specified number of days, hours, minutes and seconds to (from) the given date.
Compare Compares two specified date/time values.
GetHours Returns the hours part of the specified time value.
GetMinutes Returns the minutes part of the specified time value.
GetSeconds Returns the seconds part of the specified time value.
Now Returns the current date and time.
SetDateTimeElements Returns the Date variable having the specified date and time portions.
SetSystemDateTime Assigns the specified date and time as the system date and time.
SetTimeElements Returns the Date variable having the specified hour, minute and second.
Time Returns the current time.
TimeInterval Calculates the absolute difference between two date/time values.

Another object, aqConvert, provides methods to convert between date values and their string equivalents:

Method Description
DateTimeToFormatStr Converts the given date value to a string using the specified format.
DateTimeToStr Converts the given date value to a string.
StrToDateTime Converts the specified string to a date/time value.
StrToTime Converts the specified string to a time value.

The aqDateTime and aqConvert objects are available for all supported scripting languages, so that you can use them to operate with date values regardless of the chosen language.

VBScript has two functions with names that coincide with the names of aqDateTime’s methods. They are Time and Now. If the object name precedes the function name (for instance, aqDateTime.Now), then a TestComplete method is called; if the object name is missing (for instance, Now), then a built-in function of VBScript is called.

You can also use these and other built-in VBScript functions in your scripts. Here is a list of built-in functions that can be useful when dealing with dates:

Function Description
CDate Returns an expression that has been converted to a Variant of subtype Date.
DateAdd Returns the date to which the specified time interval has been added.
DateDiff Returns the number of intervals between two dates.
DatePart Returns the specified part of a given date.
FormatDateTime Returns an expression formatted as a date or time.
Hour Returns a whole number between 0 and 23, inclusive, representing the hour of the day.
IsDate Returns a Boolean value indicating whether an expression can be converted to a date.
Minute Returns a whole number between 0 and 59, inclusive, representing the minute of the hour.
Now Returns the current date and time according to the date and time set on your computer.
Second Returns a whole number between 0 and 59, inclusive, representing the second of the minute.
Time Returns a Variant of subtype Date indicating the current system time.
Timer Returns the number of seconds that have elapsed since midnight.
TimeSerial Returns a Variant of subtype Date containing the time for a specific hour, minute, and second.
TimeValue Returns a Variant of subtype Date containing the time.
Timer Returns the number of seconds that have elapsed since midnight.
Note: Native VBScript date-time values are stored as strings in the #MM/DD/YYYY HH:MM:SS PM/AM# format. (For example, #1/25/2005 2:17:38 PM#.) These strings are automatically converted to the variant format when required. In most cases, you can pass a VBScript date to a TestComplete routine or vice versa and get the correct results. However, initial representation of VBScript date-time values should be kept in mind.

Getting Current Time

There are two routines that return current time: Time and Now. The difference between them is that the value returned by the Now routine includes both the date and time parts, whereas the Time routine returns only the time part. The script below demonstrates how to use them.

VBScript

Sub GetTime
  Dim TimeValue, NowValue, StringTimeValue, StringNowValue, VariantTimeValue, VariantNowValue

  ' Obtain the current time
  TimeValue = aqDateTime.Time

  ' Obtain the current date and time
  NowValue = aqDateTime.Now
  
  ' Convert the returned date/time values to string values
  StringTimeValue = aqConvert.DateTimeToStr(TimeValue)
  StringNowValue = aqConvert.DateTimeToStr(NowValue)

  ' Post the converted values to the log
  Log.Message("The time obtained from the Time routine is " + StringTimeValue)
  Log.Message("The time obtained from the Now routine is " + StringNowValue)
  
  ' Convert the floating-point values to string values
  VariantTimeValue = aqConvert.FloatToStr(TimeValue)
  VariantNowValue = aqConvert.FloatToStr(NowValue)

  ' Post the converted values to the log
  Log.Message("The variant representation of TimeValue is " + VariantTimeValue)
  Log.Message("The variant representation of NowValue is " + VariantNowValue)
End Sub

Formatted Output of Time Values

The same date-time value can be represented in various formats. The aqConvert object has two methods that convert date/time values to a string using the conventional or user-defined formats. These methods are DateTimeToStr and DateTimeToFormatStr.

The DateTimeToStr method returns a string that represents the date and time according to current locale. If a date/time value holds only the time portion, the routine does not display the date part.

The DateTimeToFormatStr method allows greater flexibility since it accepts the format specifier string as one of the parameters. It is capable of forming a string of date and time portions together or in parts. To learn how the resulting format is defined, see Date and Time Format Specifiers.

Here is a sample that illustrates how to use these methods:

VBScript

Sub OutputDemo
  Dim aDateTime, Str, FormatStr

  ' Obtain the current date and time
  aDateTime = aqDateTime.Now

  ' Convert the returned date/time value to a string and post this string to the log
  Str = aqConvert.DateTimeToStr(aDateTime)
  Log.Message(Str)

  ' Convert the returned date/time value to a string using the specified format and post this string to the log
  FormatStr = aqConvert.DateTimeToFormatStr(aDateTime, "%A. %B, %d, %Y. %H:%M:%S")
  Log.Message(FormatStr)
End Sub

Encoding and Decoding Time Values

Because the date-time values are implemented as variants, special routines are required that convert the variant value to common representation. These operations are performed by the SetTimeElements, GetHours, GetMinutes and GetSeconds methods of the aqDateTime object. SetTimeElements accepts the time parts and returns a variant date/time value.

VBScript

Sub EncodeTimeDemo
  Dim myTime, EncodedTime, VariantTime

  ' Create a Date variable having the specified hour, minute and second values
  myTime=aqDateTime.SetTimeElements(13,12,25)

  ' Convert the value of the myTime variable to a string using the specified format and post this string to the log
  EncodedTime = aqConvert.DateTimeToFormatStr(myTime, "%H:%M:%S")
  Log.Message("The encoded time is "+ EncodedTime)

  ' Convert the value of the myTime variable to a variant value and post it to the log
  VariantTime = aqConvert.FloatToStr(myTime)
  Log.Message("The variant representation of it is "+ VariantTime)
End Sub

The GetHours, GetMinutes and GetSeconds methods perform a contrary operation: they accept a variant date/time value and return the time parts of that value. Here is an example of how to use these routines:

VBScript

Sub DecodeTimeDemo
  Dim CurrentTime, Hours, Minutes, Seconds

  ' Obtain the current time
  CurrentTime = aqDateTime.Time

  ' Return the hours, munutes and seconds parts of the current time value and then post them to the log
  Hours = aqDateTime.GetHours(CurrentTime)
  Minutes = aqDateTime.GetMinutes(CurrentTime)
  Seconds = aqDateTime.GetSeconds(CurrentTime)

  Log.Message(IntToStr(Minutes)+ " minute(s) and "+IntToStr(Seconds)+" second(s) have passed since the hour "+IntToStr(Hours)+" has started.")
End Sub

Modifying Time Values

The aqDateTime scripting object has a number of methods that alter the time portions of the provided date/time value. These methods are: AddHours, AddMinutes, AddSeconds and AddTime. Despite their names, these methods can both increase and decrease the corresponding time portions. When the value of an argument (Days, Hours, Minutes or Seconds) is a positive number, the methods add the specified number of days, hours, minutes or seconds to the input date/time. When an argument’s value is a negative number, the input date/time is decreased by the given number. The AddTime method allows you to change several time portions simultaneously.

The methods were designed for date/time values, so they guarantee that the resulting values will be valid. Thus, for example, changing the minutes portion automatically increases the hours portion if the resulting number of minutes exceeds 59 minutes.

The code snippet below demonstrates how to use these methods:

VBScript

Sub ModifyingTimeValues
  Dim CurrentTime, ADateTime, AlteredTime

  ' Obtain the current time
  CurrentTime = aqDateTime.Time

  ' Increase time by 30 seconds
  AlteredTime = aqDateTime.AddSeconds(CurrentTime,30)
  Log.Message("Current time: "+aqConvert.DateTimeToStr(CurrentTime))
  Log.Message("Altered time: "+aqConvert.DateTimeToStr(AlteredTime))

  ' Decrease time by 2 hours
  AlteredTime = aqDateTime.AddHours(CurrentTime,-2)
  Log.Message("Current time: "+aqConvert.DateTimeToStr(CurrentTime))
  Log.Message("Altered time: "+aqConvert.DateTimeToStr(AlteredTime))

  ' Pass both positive and negative arguments
  ' Increase time by 5 minutes (1 hour minus 55 minutes)
  AlteredTime = aqDateTime.AddTime(CurrentTime,0,1,-55,0)
  Log.Message("Current time: "+aqConvert.DateTimeToStr(CurrentTime))
  Log.Message("Altered time: "+aqConvert.DateTimeToStr(AlteredTime))

  ' Adding 10 minutes to a date value like 11:55 PM, December 31, 1999 changes the whole date
  ADateTime = aqDateTime.SetDateTimeElements(1999,12,31,23,55,00)
  AlteredTime = aqDateTime.AddMinutes(ADateTime,10)
  Log.Message("A date-time value: "+aqConvert.DateTimeToStr(ADateTime))
  Log.Message("Altered date-time: "+aqConvert.DateTimeToStr(AlteredTime))
End Sub

Comparing Time Values

To compare date/time values, use the aqDateTime.Compare method rather than comparison operators (like =, >, <, <> and others) provided by the scripting engine:

VBScript

...
r = aqDateTime.Compare(DateTime1, DateTime2)
If r > 0 Then
  ' DateTime1 > DateTime2
Else
  If r < 0 Then
    ' DateTime1 < DateTime2
  Else
    ' DateTime1 = DateTime2
  End If
End If 
...

Using the StopWatch Object

Sometimes we need to measure the time that has passed between two events, for example between the beginning and end of a test. This can be done in two ways: using the time-handling routines of the aqDateTime object and using the StopWatch object that is provided by the HISUtils plugin.

In the first case you should obtain the current time before and after the event, and calculate the interval between them (for example, with the aqDateTime.TimeInterval method).

In the second case you should create an instance of StopWatch object, start the time count using the StopWatch.Start method, execute the desired operation and then stop the counter using the StopWatch.Stop method.

Here is a code sample that demonstrates how to use both of these techniques:

VBScript

' Using the time-handling routines of the aqDateTime object
Sub MeasureTestTime1
  Dim TimeBefore, TimeAfter

  ' Obtain the current date and time before calling the test
  TimeBefore=aqDateTime.Now

  ' Call the test whose execution time you need to measure
  Call DoTest1

  ' Obtain the current date and time after calling the test
  TimeAfter=aqDateTime.Now
  Log.Message("Test1 finished.")

  ' Calculate the execution time and post it to the log
  Log.Message (aqDateTime.TimeInterval(TimeBefore, TimeAfter))
End Sub

' Using the StopWatch object
Sub MeasureTestTime2
  Dim StopWatchObj

  ' Access the StopWatch object
  Set StopWatchObj = HISUtils.StopWatch

  ' Start the time counter
  StopWatchObj.Start

  ' Call the test whose execution time you need to measure
  Call DoTest1

  ' Stop the time counter
  StopWatchObj.Stop
  Log.Message("Test1 finished.")

  ' Calculate the execution time and post it to the log
  Log.Message("Execution time: " + StopWatchObj.ToString)
End Sub

Sub DoTest1
  ' Your code here
End Sub

As you can see both methods are equivalent, but the StopWatch object has a special method called ToString, that transforms the time counter value into a string. Furthermore, the object has the Split method that allows you to get the time counter value without stopping the counter. This could be useful when displaying the elapsed time during a series of tests:

VBScript

Sub MeasureTestTime3
Dim StopWatchObj
  Set StopWatchObj= HISUtils.StopWatch

  ' Start the time counter
  StopWatchObj.Start
  For i=1 To 5
    DoTest1

    ' Return the time that has passed since the start of the time counter
    StopWatchObj.Split

    ' Calculate the elapsed time and post it to the log
    Log.Message("Iteration: "+aqConvert.IntToStr(i)+". Elapsed time: "+StopWatchObj.ToString)
    Next
  StopWatchObj.Stop
  Log.Message("Test1 finished.")

  ' Calculate the total execution time
  Log.Message("Execution time: " + StopWatchObj.ToString)
End Sub

See Also

Working With Time
VBScript - Working With Date Values
aqDateTime Object

Highlight search results