简体   繁体   中英

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?

You can use momentjs.

var moment = require('moment')

Example of using momentjs: https://jsfiddle.net/onigetoc/rzyz4wgp/

If you want to do it without any third party library then you can use following code snippet.

pass=true;
fail=false;
var responseDate = "13-Aug-2019";
var currentDate;
var months = ['Jan', 'Feb', 'Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];

if(responseCode.code === 204){
var today = new Date();
var dd = today.getDate();
var MMM = months[today.getMonth()];
var yyyy = today.getFullYear();
today = dd+'-'+MMM+'-'+yyyy;
console.log("Current Time for event is -> "+today);

if(responseDate === today){
    console.log("Pass");
    tests["ResponseDate and current date does matched "+responseDate] = responseDate === today;
}else{
    console.log("Fail");
    tests["ResponseDate and current date does not matched "+responseDate] = responseDate !== today;
}
}else{
console.log("Request failed ...!");
}

You can replace responseDate value with your runtime response date value. You can play with if condition to check greater than, equal to or smaller than operation.

we had the very same need, so, we will share our complete solution. It run using the Test Option at postman, in this case, it does use the data from the get and process it using Moment.js , basically:

  1. Retrieve the data using Get
  2. Check if the JSON response if ok
  3. Load moment.js
  4. Add 20 days to the date value
  5. Compare it the date is bigger than today
  6. Create an array with selected records
  7. Post to the Restfull database (you can test Get and Post with http://restdb.io )

Test code Sample

var moment = require('moment');
pm.test("response must be valid and have a body", function () {
     pm.response.to.be.ok; 
     pm.response.to.be.withBody;
     pm.response.to.be.json;
});
var slots = pm.response.json();
var myPost = [];
var todo = [
    {
      "_id": "5d13e83bb1c3633400002841"
    }
  ];
var hoje = moment();
for (let thisItem of slots) {
    var changedOk = moment(thisItem._changed).add(20, 'days');
    if (moment(changedOk).isBefore(hoje))
    myPost.push( {
        _id: thisItem._id,
        toDo : todo,
        approved: true,
        onHalt: true,
        p: false        
    });
}
console.log(myPost);
pm.sendRequest({
    url: 'https://mydbase-0000.restdb.io/rest/slots',
    method: 'POST',
    header:    { 'cache-control': 'no-cache',
                'content-type': 'application/json',
                'x-apikey': 'xxxxxxxxxxxxxxxxxxxxxx'},
    body: {
        mode: 'raw',
        raw: JSON.stringify(myPost)
    }
}, function (err, res) {
    console.log(res);
});

You can use the Postman echo API to do this - please look at the given link and see If this is what you are looking for.

https://docs.postman-echo.com/?version=latest#b709b99c-3347-40fc-2c21-98ceb7f9e267

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM