DelphiScript - Working With Time Values

Applies to TestComplete 15.63, last modified on April 10, 2024

In this topic you will learn how to work with time values in DelphiScript 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.

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.

DelphiScript

procedure GetTime;
var TimeValue, NowValue, StringTimeValue, StringNowValue, VariantTimeValue, VariantNowValue: OleVariant;
begin
  // 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;

Formatted Output of Time Values

The same date-time value can be represented in various formats. The aqConvert object has two methods that convert the date-time value 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 the date-time value holds only time portion, then 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:

DelphiScript

procedure OutputDemo;
var aDateTime, Str, FormatStr: OleVariant;
begin
  // 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;

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. The SetTimeElements accepts the time parts and returns the variant date-time value.

DelphiScript

procedure EncodeTimeDemo;
var myTime, EncodedTime, VariantTime: OleVariant;
begin
  // 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;

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

DelphiScript

procedure DecodeTimeDemo;
var CurrentTime : TDateTime;
    Hours, Minutes, Seconds:Integer;
begin 
  CurrentTime := aqDateTime.Time;

  // Return the hours, minutes 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(aqConvert.IntToStr(Minutes)+ ' minute(s) and '+aqConvert.IntToStr(Seconds)+' second(s) have passed since the hour '+aqConvert.IntToStr(Hours)+' has started.');
end;

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 the respective argument (Days, Hours, Minutes or Seconds) is positive number, then the methods add the specified number of days, hours, minutes or seconds to the input date-time. When the argument’s value is negative, then the input date-time is decreased by the given number. The AddTime method allows to change several time portions simultaneously.

The methods are designed especially for date-time values, and guarantee a valid resulting value. Thus, for example, changing the minutes portion automatically increases the hours portion if the resulting number of minutes exceeds 59 minutes.

The code fragment below demonstrates how to use these methods:

DelphiScript

procedure ModifyingTimeValues;
var CurrentTime, ADateTime, AlteredTime: TDateTime;
begin
  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));

  // Passing 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 value: '+aqConvert.DateTimeToStr(AlteredTime));
end;

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:

DelphiScript

r := aqDateTime.Compare(DateTime1, DateTime2);
if r > 0 then
  // DateTime1 > DateTime2;
else
begin
  if r < 0 then
    // DateTime1 < DateTime2;
  else
    // DateTime1 = DateTime2;
end;

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:

DelphiScript

procedure DoTest1;
begin
  // Your code here
end;

// Using the time-handling routines of the aqDateTime object
procedure MeasureTestTime1;
var TimeBefore, TimeAfter: TDateTime;
begin
  // Obtain the current date and time before calling the test
  TimeBefore:=aqDateTime.Now;

  // Call the test whose execution time you need to measure
  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;

// Using the StopWatch object
procedure MeasureTestTime2;
var StopWatchObj: OleVariant;
begin
// Access the StopWatch object
  StopWatchObj := HISUtils.StopWatch;

  // Start the time counter
  StopWatchObj.Start;

  // Call the test whose execution time you need to measure
  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;

As you can see both methods are equivalent, yet the StopWatch object has a special method 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:

DelphiScript

procedure MeasureTestTime3;
var StopWatchObj: OleVariant;
    i: integer;
begin
  StopWatchObj := HISUtils.StopWatch;

  // Start the time counter
  StopWatchObj.Start;
  for i:=1 to 5 do
    begin
    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)+'. Time elapsed: '+StopWatchObj.ToString);
    end;
  StopWatchObj.Stop;
  Log.Message('Test1 finished.');

  // Calculate the total execution time
  Log.Message('Execution time: ' + StopWatchObj.ToString);
end;

See Also

Working With Time
DelphiScript - Working With Date Values
aqDateTime Object

Highlight search results