Search code examples
javascriptpostmanpostman-collection-runner

How to compare two dates in Postman


I have a scenario where I need to compare a date from an API response with today's date and check whether it is less than or equal.

The API response will give me a JSON object and in that JSON the key " License" will contain a date in the format "13-Aug-2019", I need to compare this date with today's date and if today's date is greater than "13-Aug-2019" gives a fail in the test results.

Below is the code I wrote to get the date in the license string and today's date,

Var body = JSON.parse(response Body);
Var body date=body["license"]
//Sample license value is " license cs code1 version 13-aug- 
2018 cnts ......"
var words = bodydate.split(' ');
license_valid_till=words[4]; // This will get the string 13-aug- 
2019

console.log(license_valid_till)

var ts = new Date();
var part=ts.toDateString();
var dpart = part.split(' ');
today_date=dpart[2] + "-" +dpart[1] +"-"+ dpart[3];
//This will get the string 12-aug-2019
console.log(today_date)

Now my question is how can I compare these two values, any suggestions will be of great help?


Solution

  • I have a similar scenario: I need to compare two dates in postman, dates in a format like "2022-01-16T19:40:51.816".

    So I use this:

    // (dates from JSON for my case)
    // var date1 = "2022-01-16T19:40:51.816";
    // var date2 = "2022-01-16T17:40:51.816";
    // (today for your case)
    // var today = new Date();
    pm.expect(Date.parse(date1)).to.be.above(Date.parse(date2));