JavaScript - Working With Time Values

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

In this topic you will learn how to work with time values in JavaScript 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 date and time parts, whereas the Time routine returns only the time part. The script below demonstrates how to use them.

JavaScript

function GetTime()
{
  var 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);
}

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 its current location. If the date-time value only has the time portion, then the routine does not display the date.

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:

JavaScript

function OutputDemo()
{
  var 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);
}

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.

JavaScript

function EncodeTimeDemo()
{
  var 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)
}

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:

JavaScript

function DecodeTimeDemo()
{
  var CurrentTime, Hours, Minutes, Seconds;

  // Obtain the current time
  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(IntToStr(Minutes)+ " minute(s) and "+IntToStr(Seconds)+" second(s) have passed since the hour "+IntToStr(Hours)+" has started.")
}

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 a 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 you 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:

JavaScript

function ModifyingTimeValues()
{
    var CurrentTime, Time, AlteredTime;

    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
    Time=aqDateTime.SetDateTimeElements(1999,12,31,23,55,00);
    AlteredTime=aqDateTime.AddMinutes(Time,10);
    Log.Message("Time: "+aqConvert.DateTimeToStr(Time));
    Log.Message("Altered time: "+aqConvert.DateTimeToStr(AlteredTime));
}

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:

JavaScript

r = aqDateTime.Compare(DateTime1, DateTime2);
if(r > 0)
  // DateTime1 > DateTime2
else
  if(r < 0)
    // DateTime1 < DateTime2
  else
    // equal(DateTime1, DateTime2)

This note does not concern the Date objects provided by the JavaScript engine. This object is used to store date and time values. To compare Date objects, use the features provided by the engine.

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 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:

JavaScript

// Using the time-handling routines of the aqDateTime object
function MeasureTestTime1()
{
  var 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
  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));
}

// Using the StopWatch object
function MeasureTestTime2()
{
  // Access the StopWatch object
  var 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());
}

function DoTest1()
{
  // Your code here
}

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:

JavaScript

function MeasureTestTime3()
{
  var StopWatchObj = HISUtils.StopWatch;

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

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

Converting to Date Object Containing the Time Portion

JavaScript has a native Date object that was especially created to hold the date-time values and has its own methods to manage dates and time. A complete description of the object is in the Date Object article on the Mozilla Developer Network website. The JavaScript - Working With Date Values topic describes how to convert variant date values into instances of the Date object and vice versa. However, those routines only deal with the date part. Below is the code for the routines that keep both the date and time parts:

JavaScript

function ToDateObject (InputDate)
{
  var DateObj;
  var Day, Month, Year;
  var Hour, Minute, Second;

  // Parse variant date portion into components
  Day=aqDateTime.GetDay(InputDate);
  Month=aqDateTime.GetMonth(InputDate);
  Year=aqDateTime.GetYear(InputDate);
  // Parse variant time portion into components
  Hour=aqDateTime.GetHours(InputDate);
  Minute=aqDateTime.GetMinutes(InputDate);
  Second=aqDateTime.GetSeconds(InputDate);
   
  // Create a Date object
  DateObj = new Date();

  //Assign values to object
  DateObj.setDate(Day);
  DateObj.setMonth(Month-1);
  DateObj.setFullYear(Year);
  DateObj.setHours(Hour, Minute, Second);
  
  return DateObj;
}

function ToVariantDate (InputDateObj)
{
  var VariantDate, Y, Mnth, D, H, Mins, S;
  
  Y = InputDateObj.getFullYear();
  Mnth = InputDateObj.getMonth()+1;
  D = InputDateObj.getDate();
  H = InputDateObj.getHours();
  Mins = InputDateObj.getMinutes();
  S = InputDateObj.getSeconds();
    
  VariantDate = aqDateTime.SetDateTimeElements(Y, Mnth, D, H, Mins, S);
  return VariantDate;
}

See Also

Working With Time
JavaScript - Working With Date Values
aqDateTime Object

Highlight search results