HOWTO: Compare 2 dates in different formats in TestComplete

Suppose you have two date time strings in different formats and you need to compare if they are the same. Here's a function the code that will do this task for you.
NOTE: This code assumes that your dates are in the following formats: 12/31/2011 12:00:00 AM and 31-December-2011-00:00:00

To tackle this task, we're going to parse above mentioned date string and get number of milliseconds since January 1, 1970. Once we have our date in milliseconds, compare the two numbers and see if dates are same or different.

JavaScript has a function Date.parse(datestring) that does the conversion for us, but as you may have already guessed, this function is going to choke on the second date string. To get around it, I used a regular expression that would separate every piece of the date. Once I have all my pieces, I would create a date string that is accepted by the above mentioned function.

So, without further delay, here's the my function:

-
function compareDates () {
  // define our date strings
  var date1 = "5/31/2015 12:00:00 AM";
  var date2 = "31-May-2015-00:00:00";
 
  // define a pattern that would identify our date string
  var pattern = /^(\d+)-(\w*)-(\d+)-(\d+:\d+:\d+)$/;
 
  // create a regular expression object
  var regexp = new RegExp(pattern);
 
  // make sure that our regular expression will match the date string
  if (regexp.test(date2)) {
    // Execute regular expression
    var res = regexp.exec(date2);
 
    // create a new date string in a form of Month day, year
    var date2New = res[2] + " " + res[1] + ", " + res[3] + " " + res[4];
 
    // compare our dates
    if (Date.parse(date1) === Date.parse(date2New)) {
      Log.Message("Dates are identical!");
    }
    else {
      Log.Error("Dates didn't match.");
    }
  }
  else {
    Log.Error("Regular expression didn't match date.");
  }
}

Comments